Coding – Xenioo Sun, 23 May 2021 13:07:38 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.12 /wp-content/uploads/2022/02/cropped-badge_611x611-32x32.png Coding – 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
Accepting Stripe Payment In Your Chatbot /accepting-stripe-payment-in-your-chatbot/ /accepting-stripe-payment-in-your-chatbot/#respond Mon, 17 Dec 2018 08:41:17 +0000 https://wp.xenioo.com/?p=995 Many of our customer’s chatbots are lately evolving from generic marketing or first contact automation to fully experienced sales assistants, pointing to specific products and helping the user pick the right one. While all processes and approaches vary from one to another, all of them at some point come to terms with payment management. At some point, you will want to process your user payment for a product, a subscription or a service. This post will explain in detail how ...

Read MoreAccepting Stripe Payment In Your Chatbot

The post Accepting Stripe Payment In Your Chatbot appeared first on Xenioo.

]]>
Many of our customer’s chatbots are lately evolving from generic marketing or first contact automation to fully experienced sales assistants, pointing to specific products and helping the user pick the right one.

While all processes and approaches vary from one to another, all of them at some point come to terms with payment management.

At some point, you will want to process your user payment for a product, a subscription or a service. This post will explain in detail how you can do easily with Stripe and Xenioo. 

For the sake of the example, we will just assume that you’ve already a valid Stripe account to be used as a test. If not, go ahead and signup: its very quick and free while you don’t have any real transaction.

Payment Process

The payment process we would like to build is very typical: the user buys something from your chatbot and gets presented with a button to proceed to payment.

The payment is processed externally, on a secure website page. Once the payment has been approved, the external page closes and the chatbot continues.

To implement this we will need:

  • The Xenioo chatbot managing the conversation
  • A page built to process the Stripe payment
  • A mean of sending back the payment processing details to Xenioo

Creating the Chatbot

The first thing we will do is create a new chatbot and create a button template with just one URL button that will open an external page. This external page needs to be on an external website and will contain the code required to process the Stripe payment.

Make sure to specify the correct address in the URL button without forgetting the ?cid={{user_id}} part. With this syntax, we are basically building a link that contains the unique user id that Xenioo uses to identify a single conversation and we will use that later to link back.

Receiving the data

Now that we have got the link to exit the chatbot, we need to create something that can give our chatbot a way to receive external information. To do this, we’ll go ahead and use a very handy type of Broadcast: the On Demand Broadcast.

This particular type of broadcast can be activated by calling a simple REST web-hook and can be manipulated to accept both dynamic audiences and variables.

We do not need to really fully process our payment but we want to see the successful result in our chatbot. So in the Design section of our broadcast, we will be creating an interaction capable of giving us some feedback and, for now, even some debug information.

Our broadcast will be called externally by our page, so make sure to specify the acceptable host names filter in the details section. You really do not want anyone but your website to call this broadcast.

When all it is done, save your broadcast making sure it is enabled. It is time to move to the real payment section with our custom page.

Building the Stripe Page

Our very basic chatbot is ready and now we need to create the page that will manage the payment. You will find a host of examples on the Stripe website but we will need to add some additional code to have a redirect of the data to Xenioo.

You can find a snippet of the HTML source below: just make sure to change the API key with your Stripe TEST key and the broadcast URL with the one that Xenioo has given to your chatbot.

No worries, our GitHub repository contains eveything. Nearly all of the code here is related to Stripe payment library but we can see the very interesting Xenioo bit here:

What is happening here is the real magic of the On Demand Broadcast of Xenioo.

By calling the given hook using a simple Ajax function, we are actually firing the broadcast. Since we do not want the broadcast to be sent to all users, we are supplying a dynamic audience, building a filter where user_id equals the value of the parameter we just supplied on our url.

As the broadcast is fired, Xenioo will target only the users meeting the criteria and since user_id is unique, only the specific user that initiated that specific payment will receive a notification.

Additionally, since we want to keep payment details in our chatbot, we are also sending a dynamic variable value in our payload called “stripe_data” that will contain all the Strip payment JSON details.

We can later use this token to verify the payment or use it to submit more data to our back-end for invoicing.

Not Just Stripe

Our general approach will work with just any supported chatbot platform so go ahead and publish your chatbot wherever you like most.

Just remember that WhatsApp will not display buttons so if that is your platform of choice, change the URL button with a simple text that will be displayed as a link.

If instead, you like to create a Web chatbot, you can probably skip the multi-page approach and move directly to using a Client Script Action to activate Stripe processing directly on the same page.

Also, this data collection method we’ve just shown is not just about Stripe and payments but can be used for just about anything that needs to be done outside your chatbot. A special form for data collection or an external page that needs to be filled before continuing: all of these scenarios can be managed with this approach!

Sources

You can find this chatbot backup(that you can restore back into your Xenioo account) and the example pages on our GitHub repository.

The post Accepting Stripe Payment In Your Chatbot appeared first on Xenioo.

]]>
/accepting-stripe-payment-in-your-chatbot/feed/ 0
How to Create a WhatsApp Dynamic Chatbot to boost your channel /creating-a-whatsapp-dynamic-chatbot/ /creating-a-whatsapp-dynamic-chatbot/#respond Tue, 11 Dec 2018 16:40:56 +0000 https://wp.xenioo.com/?p=991 We’ve seen multiple times how easy is to add text and visual elements to your chatbot using Xenioo Chatbot Designer. Creating a functional WhatsApp dynamic chatbot or multi-platform chatbot for Facebook, Telegram or Web become a task of few minutes. But what if the text or even the options that we are going to show to our users are dynamic? What if the choices we’re going to display depend on some kind of dynamic data? Keep on reading: we’re going to ...

Read MoreHow to Create a WhatsApp Dynamic Chatbot to boost your channel

The post How to Create a WhatsApp Dynamic Chatbot to boost your channel appeared first on Xenioo.

]]>
We’ve seen multiple times how easy is to add text and visual elements to your chatbot using Xenioo Chatbot Designer. Creating a functional WhatsApp dynamic chatbot or multi-platform chatbot for Facebook, Telegram or Web become a task of few minutes.

But what if the text or even the options that we are going to show to our users are dynamic? What if the choices we’re going to display depend on some kind of dynamic data?

Keep on reading: we’re going to see exactly how we can do that with Xenioo.

Preparing Dynamic Data

For our example, we’re going to need some kind of data that can change outside of the chatbot design. The typical source would be some backend that feeds data to your chatbot conversation and to simulate that, we’re going to publish some dynamic data online.

The fastest way to do that is to use Sheetlabs: this service can quickly turn tabular data (such as a typical Excel file) into an online data source you can read and update using APIs.

A basic account is free and perfectly fine for our example.

colors

In my example, I’ve created a new table with just a color id and color name. You can go of course much further and make the table as complex as you like.

Just remember, after uploading your data, to enable API access and take note of the endpoint that has been created for you.

Retrieving Information

Now that our data is ready, we can switch to Xenioo to create our chatbot and the first thing we need to do is, of course, adding a generic API Call Action.

We will use our API URL as a source, and push all the data into a Xenioo variable. If you are not sure about how the data is returned, go ahead and use a standard text output to check what the API call returns.

setting color variables for whatsapp dynamic chatbot

Once the data is available to Xenioo, all there is to do is parse and transform it into dynamic contents. To do this, as we did in other situations, we will be using Xenioo Cloud Scripting Action.

We will be retrieving our variable data value, transform it into a real object and create content on the fly.

You can see the full code below:

What we are doing in our code is using every entry of colors (which is every color in our table) and join that into a text that will be dynamically added to our chat by the method AddReplyPart of the conversation object.

After the code executes, you will see the result in your chat.

colors output in whatsapp dynamic chatbot

The message bubble listing all colors wasn’t in our chatbot design: we just created that on the fly. Different users may see different options because of different other variables and flows: the possibilities are endless!

Picking an Option

Now that we can display our options to user all is left to do is to let him pick one and react to the choice.

We are going to need a Generic Input Action but how can we make sure that our user chooses only the dynamic options we’ve just created?

To do this, we’re going to slightly change our Cloud Scripting Action like below:

As you see,  while creating the text output we are also creating a simple expression based on id and color. The resulting variable will contain something like this: (A|Red|B|Blue|C|Yellow|D|Green|E|Purple).

Since Xenioo allows the use of variables in every part of any action, we will pass the expression directly as the Control Expression value of our Generic Input Action.

Let’s just add a final text for checking our use reply and its done! A fully dynamic chatbot content ready for WhatsApp prime-time 🙂

testing whatsapp dynamic chatbot

What About Buttons?

WhatsApp currently does not support buttons. You can very well see by the hints and helps that Xenioo will supply while designing your chatbot.

If your platform of choice allows them, you’re more than welcome to adapt our little example accordingly.

We have prepared some interesting variations for you on our GitHub free source repository.

The post How to Create a WhatsApp Dynamic Chatbot to boost your channel appeared first on Xenioo.

]]>
/creating-a-whatsapp-dynamic-chatbot/feed/ 0
Come creare un chatbot dinamico per Whatsapp /come-creare-un-chatbot-dinamico-per-whatsapp/ /come-creare-un-chatbot-dinamico-per-whatsapp/#respond Tue, 11 Dec 2018 16:40:56 +0000 https://wp.xenioo.com/?p=991 In un nostro precedente articolo abbiamo già parlato di come creare in pochi minuti un primo chatbot per Whatsapp attraverso Xenioo. Abbiamo inoltre più volte raccontato come le funzionalità avanzate del designer di chatbot di Xenioo rendono davvero semplice la creazione di elementi testuali e visuali. Ma come comportarci quando il testo o le opzioni da visualizzare agli utenti dipendono da dati dinamici che magari dobbiamo recuperare da una qualche fonte online? Prepariamo i dati dinamici per il chatbot Per ...

Read MoreCome creare un chatbot dinamico per Whatsapp

The post Come creare un chatbot dinamico per Whatsapp appeared first on Xenioo.

]]>
In un nostro precedente articolo abbiamo già parlato di come creare in pochi minuti un primo chatbot per Whatsapp attraverso Xenioo.

Abbiamo inoltre più volte raccontato come le funzionalità avanzate del designer di chatbot di Xenioo rendono davvero semplice la creazione di elementi testuali e visuali.

Ma come comportarci quando il testo o le opzioni da visualizzare agli utenti dipendono da dati dinamici che magari dobbiamo recuperare da una qualche fonte online?

Prepariamo i dati dinamici per il chatbot

Per il nostro bot di esempio abbiamo bisogno di una fonte dati, essenzialmente un database, che si trovi al di fuori del chatbot stesso.

La tipica sorgente di una simile fonte dati potrebbe essere un qualsiasi backend dotato di API Restful e quindi in grado di comunicare facilmente con il chatbot.

Il modo più veloce per realizzare il nostro prototipo è quello di utilizzare Sheetlabs. Sheetlabs è un servizio online che consente di creare velocemente tabelle di dati, in modo simile a fogli Excel, e trasformarli in sorgenti dati che possono essere lette ed aggiornate via API.

Potete creare un account base, gratuito e perfettamente funzionante per il nostro scopo.

Creato l’account, andremo a creare una nuova tabella per inserire una lista di colori, identificandoli attraverso la coppia di campi Id e Colore. Si tratta di un esempio molto semplice, per casi reali potrete creare strutture dati più complesse.

Ricordatevi, dopo aver creato e riempito la tabella, di abilitare l’accesso API e prendere nota dell’endpoint(l’URL) che è stato creato appositamente per voi da Sheetlabs.

Leggiamo i dati dal chatbot

Ora che i dati sono pronti, possiamo tornare in Xenioo per creare il chatbot. Il chatbot chiederà all’utente un colore da scegliere da una lista. Questa lista sarà dinamica e caricata dalla sorgente dati precedentemente creata.

La prima azione che dovremo aggiungere sarà ovviamente una generica API Call Action.

Per chi non si ricordasse come funziona, può sempre ripassare quanto scritto nella nostra lezione a riguardo.

Per configurare l’azione, indicheremo nel campo API URL l’endpoint che ci viene fornito da Sheetlabs. I risultati della chiamata all’API verrano inseriti in una apposita variable che creeremo per l’occorrenza. Se non siete sicuri del formato con la quale i dati vengono ritornati da Sheetlabs, è sufficiente usare una Text Action per stampare il risultato come risposta del chatbot.

Ora che i dati sono disponibili in Xenioo, dobbiamo analizzarli e trasformarli in un contenuto dinamico.

Per fare questo dobbiamo scrivere del codice Javascript utilizzando l’azione Cloud Scripting, di cui abbiamo parlato in una delle nostre lezioni iniziali.

In pratica il codice si occuperà di recuperare il valore dalla variabile contenente il risultato della chiamata all’ API, trasformarlo in un oggetto Javascript e creare il contenuto da visualizzare nella chat al volo.

Potete vedere il codice qui sotto:

var colors = JSON.parse( conversation.GetVariableValue( "colors_data" ) );

var txt = "";
var input = "";

for( var i=0; i < colors.length; i++ ){
  /* We build the message text */
  /* The \r at the end is required for multiline in the bubble */
  txt += colors[i].colorid + ") " + colors[i].color + "\r"; 
  input += colors[i].colorid + "|" + colors[i].color + "|";
}

conversation.AddReplyPart(txt);

Cosa fa esattamente questa porzione di codice? In pratica, per ogni colore ritornato (e quindi per ogni colore presente nella tabella creata su Sheetlabs) creiamo un testo che verrà aggiunto alla nostra chat grazie al metodo AddReplyPart dell’oggetto globale conversation.

Se proviamo ad eseguire il chatbot in preview, vedremo il risultato come nell’immagine seguente.

La bolla di testo con l’elenco dei colori non è stata creata preventivamente nel chatbot, ma è stata generata in tempo reale.

Utilizzando variabili e dati più compelssi è possibile fare in modo che utenti diversi vedano, per esempio, opzioni differenti, e cosi via. Le possibilità sono infinite!

Come selezionare una delle opzioni

Ora che abbiamo visualizzato dinamicamente le opzioni all’utente, non ci resta altro che gestire come l’utente le possa selezionare e come il bot risponda di conseguenza.

Ci serviremo dell’ azione Generic Input, ma come possiamo essere sicuri che l’utente possa scegliere unicamente tra le opzioni che sono state dinamicamente create?

Per fare questo, dobbiamo modificare leggermente il nostro script, come mostrato qui sotto.

var colors = JSON.parse( conversation.GetVariableValue( "colors_data" ) );

var txt = "";
var input = "";

for( var i=0; i < colors.length; i++ ){
  /* We build the message text */
  /* The \r at the end is required for multiline in the bubble */
  txt += colors[i].colorid + ") " + colors[i].color + "\r"; 
  input += colors[i].colorid + "|" + colors[i].color + "|";
}

conversation.SetVariable ("colors_input", "(" + input + ")");

conversation.AddReplyPart(txt);

Come potete vedere, abbiamo aggiunto una riga in più:

conversation.SetVariable ("colors_input", "(" + input + ")");

Questa riga di codice crea una nuova variabile, “colors_input”, contenente una semplice espressione regolare basata sull’ ID e nome del colore. Questa variabile conterrà qualcosa di simile a:
(A|Red|B|Blue|C|Yellow|D|Green|E|Purple).

Dal momento che Xenioo permette l’utilizzo di variabili in ogni parte della configurazione di un’azione, useremo questa variabile per passare l’espressione direttamente nel campo Control Expression dell’azione Generic Input.

Aggiungiamo poi un testo finale per la verica della risposta dell’utente ed abbiamo finito!

Abbiamo creato in pochi passi un chatbot a contenuto dinamico per Whatsapp, e non solo. Infatti, questo chatbot di esempio potrebbe essere pubblicato senza modifiche ulteriori su qualsiasi delle altre piattaforme chatbots che Xenioo supporta.

E se volessimo usare dei bottoni?

Whatsapp al momento non supporta la visualizzazione di bottoni nella sua chat, come peraltro è evidenziato dalle icone rosse oppure arancioni visibili nel designer di Xenioo per ogni azione.

Se intendete realizzare un chatbot dinamico per una delle piattaforme che supporta bottoni, come Facebook Messenger, Telegram oppure Siti Web, è sufficiente adattare nel modo adeguato questo esempio.

A tal proposito, potete andare a vedervi una variante che abbiamo preparato per voi e che permette l’aggiunta di bottoni dinamici.

Il chatbot di esempio descritto in questo articolo lo trovate invece qui, pronto da essere ripristinato all’interno del vostro account Xenioo.

The post Come creare un chatbot dinamico per Whatsapp appeared first on Xenioo.

]]>
/come-creare-un-chatbot-dinamico-per-whatsapp/feed/ 0
Integrate your chatbot with everything using Xenioo Custom Channel /integrate-your-chatbot-with-everything-using-xenioo-custom-channel/ /integrate-your-chatbot-with-everything-using-xenioo-custom-channel/#respond Sat, 20 Oct 2018 09:22:02 +0000 https://wp.xenioo.com/?p=959 The Xenioo Custom Channel allows any application capable of making simple RESTful https calls to integrate and interact with a chatbot engine platform. Using the Xenioo Custom Channel you will be controlling the way the conversation will be displayed to the user as well as being able to change runtime variables anytime. In this post, we will go into every detail of how the Xenioo Custom Channel works and how to use it. General Approach You will be communicating with Xenioo to ...

Read MoreIntegrate your chatbot with everything using Xenioo Custom Channel

The post Integrate your chatbot with everything using Xenioo Custom Channel appeared first on Xenioo.

]]>
The Xenioo Custom Channel allows any application capable of making simple RESTful https calls to integrate and interact with a chatbot engine platform.

Using the Xenioo Custom Channel you will be controlling the way the conversation will be displayed to the user as well as being able to change runtime variables anytime.

In this post, we will go into every detail of how the Xenioo Custom Channel works and how to use it.

General Approach

You will be communicating with Xenioo to RESTful https API calls. Each API must include some fields that will let Xenioo know of what chatbot we are talking about and, eventually, of what user we are managing the conversation.

Each call made to your Xenioo chatbot must include the following headers:

HeaderValueDescription
AuthorizationBearer [APIKEY]This is the API Key you can copy from your Xenioo API publishing dialog.
Content-Typeapplication/jsonAll data exchanged with Xenioo must be of this type
user-id[any string]This is the current chat user id. If no value is specified, Xenioo will create a new user

Retrieving your chatbot configuration

You chatbot basic configuration, as specified in your Xenioo designer, can be retrieved using the config endpoint as follows:

curl -X GET \
  https://app.xenioo.com/apihook/config \
  -H 'Authorization: Bearer [APIKEY]' \

Since this is a global configuration, you don’t need to specify the current user-id here. Xenioo reply to this request will be similar to this one:

{
    "Name": "My Awesome Bot",
    "EnableTypeSpeed": true,
    "WordsPerMinute": 800,
    "Avatar": "https://app.xenioo.com/api/assets/8e23ff8b3ee7_60f1113c-8e6e-46ce-bf19-a53da5ff4ed0.jpg",
    "Version": 96,
    "DefaultBehaviour": {
        "Name": "My Top Behaviour",
        "APIKey": "[Behaviour API Token]"    }
}
fieldtypedescription
NamestringThe name of your chatbot
EnableTypeSpeedbooleanIndicates if the chatbot is configured to use typespeed simulation. If so, TypeDelay will be valued for actions where necessary
WordsPerMinutenumberThe number of words per minute your chatbot can write. This affects the TypeDelay parameter value
AvatarstringThe url of the avatar specified under your chatbot general settings
VersionnumberThe version number of your chatbot. This number is automatically increased by Xenioo
DefaultBehaviourobjectThe name and the API Key associated to your default chatbot Behaviour. You can use the API Key to forcefully redirect your chatbot conversation to another Behaviour

Initiating Chat

The fist connection to your chatbot chat must be done by calling the chat endpoint using the previously specified headers.

This endpoint, called without sending any data will reset the conversation to the starting point. If the user-id is specified in this call, the conversation will be reset but historic conversation will be kept in the Xenioo conversation history interface.

curl -X POST \
  https://app.xenioo.com/apihook/chat \
  -H 'Authorization: Bearer [APIKEY]' \
  -H 'Content-Type: application/json' \
  -H 'user-id: some-user-id'

If you wish instead to continue a previous conversation with a know user you can add the READY command to the request as below. In this case, Xenioo will not reset the conversation and return the full history as first reply.

curl -X POST \
  https://app.xenioo.com/apihook/chat \
  -H 'Authorization: Bearer [APIKEY]' \
  -H 'Content-Type: application/json' \
  -H 'user-id: some-user-id' \
  -d '{	"Command":"READY"}'

A successful reply from Xenioo may look like this:

{
    "Parts": [
        {
            "Type": 0,
            "Text": "Hello...I am Xenioo 9000.",
            "TypeDelay": 300,
            "BehaviourName": "New Bot Behaviour",
            "InteractionName": "Start Interaction",
            "Parts": []
        }
    ],
    "UserId": "some-user-id",
    "Creation": "2018-10-05T14:43:43.7057755+01:00",
    "EnableUserChat": true,
    "ControlType": 0}

The root reply fields have the following format:

fieldtypedescription
PartsarrayThis is an array of 1 or more chat parts. Each chat part is usually a Xenioo Action Result
UserIdstringThe user-id of the current user chatting with you. If you did not create it yourself store it and re-use it for subsequent calls
CreationdatetimeThe Xenioo reply creation date and time
EnableUserChatbooleanThis may change depending on your chatbot design. You should comply to the chabot designer choices by either allowing or forbidding an open reply from the user
ControlTypenumberThe control state of the chatbot. 0-Xenioo, 1-Operator Requested, 2-Operator Taken Over

Chatting

Once the chat control is given to the user, he can interact with your chatbot in two ways: executing a command or saying something (sending a text).

After acquiring the user input, you can relay it to Xenioo using the same connection endpoint, with the following syntax:

curl -X POST \
  https://app.xenioo.com/apihook/chat \
  -H 'Authorization: Bearer [APIKEY]' \
  -H 'Content-Type: application/json' \
  -H 'user-id: some-user-id' \
  -d '{  	"Text":"Hello there!"  }'

Depending on how you’ve implemented your chatbot reactions and interactions the answer may change but will always be compliant to the previous reply fields. If your user has instead any means to click on chat buttons you’ve implemented or on Carousel contents you must forward to Xenioo the command payload as follows:

curl -X POST \
  https://app.xenioo.com/apihook/chat \
  -H 'Authorization: Bearer [APIKEY]' \
  -H 'Content-Type: application/json' \
  -H 'user-id: some-user-id' \
  -d '{	"Command":"3131292d-945e-4b6b-9f78-7f5eacebf5b6"}'

Command payloads are always GUID values generated by Xenioo. If the command payload is recognized, the command will trigger and the conversation continues, according to the flow you’ve designed.

Variables and Tags

You can update (or create new) variables value or conversation tags using the status endpoint like in the example below:

curl -X POST \
  https://app.xenioo.com/apihook/status \
  -H 'Authorization: Bearer [APIKEY]' \
  -H 'Content-Type: application/json' \
  -H 'user-id: some-user-id' \
  -d '{	"UpdateType":"[type]",	"Name":"variable_name",	"Value":"variable_value"}'

The UpdateType parameter specifies the type of operation to be done on the chatbot conversation. You have four different update types as specified in the table below:

typedescription
set-varUpdates or set the variable with name specified in Name and value specified in Value
de-varDrops the variable with name as specified in Name field
set-tagAdds a new tag named Name in the conversation
del-tagRemoves the specified tag

Variable changes are immediate and can even alter variables that have been created or changed during last interaction execution.

Time To Try it!

As you you’ve seen, Xenioo Custom Channel really has all the tools that allow you to build your chatbot the way you want, leaving the hard work to us!

Ready to give it a try? Head right away to our GitHub repository to get the full source code and examples in both .NET and Python. If you are using .NET, there’s also a very handy Nuget Package ready to be downloaded.

The post Integrate your chatbot with everything using Xenioo Custom Channel appeared first on Xenioo.

]]>
/integrate-your-chatbot-with-everything-using-xenioo-custom-channel/feed/ 0