Opensource Chatbot 👉Rocket.Chat + Google DialogFlow ) 🚀
Instalación de RocketChat
Bueno, como lo hemos hecho en otras ocasiones, instalaremos RocketChat usando el Helm Chart para ello, y lo modificaremos. Así, nuestro `values.yaml` quedará:
# https://github.com/RocketChat/helm-charts/blob/master/rocketchat/values.yaml
clusterDomain: marketshop.local
host: chat.patagon.dev.io
smtp:
enabled: true
username: xxx
password: yyy
host: email-smtp.us-east-1.amazonaws.com
port: 587
mongodb:
enabled: true
clusterDomain: marketshop.local
auth:
rootPassword: abcd1234
username: rocketchat
password: abdc1234
database: rocketchat
architecture: replicaset
replicaCount: 1
replicaSetName: rs0
persistence:
enabled: true
storageClass: nfs-client
accessMode: ReadWriteOnce
size: 8Gi
volumePermissions: {enabled: true}
persistence:
enabled: true
storageClass: nfs-client
ingress:
enabled: true
annotations:
kubernetes.io/ingress.class: traefik
traefik.ingress.kubernetes.io/router.entrypoints: websecure
hosts:
- host: chat.patagon.dev
paths:
- path: /
pathType: ImplementationSpecific
path: /
type: ClusterIP
port: 80
Luego agregamos el repositorio, y lo instalamos:
helm repo add rocketchat https://rocketchat.github.io/helm-charts
helm upgrade -i rocketchat rocketchat/rocketchat -f values.yaml
Y listo ! ya está rocketchat instalado:
Configuración
Una vez instalado Rocket.Chat, se debe habilitar la aplicación de DialogFlow:
Se deben completar los datos de configuración. Más info en esta guía.
Google Dialogflow
Google Dialogflow es un motor de mensajería. Se deben crear las intencioes (o "Intents") para que se pueda desarrollar una conversación según un flujo predefinido:
Se usan las frases de entrenamiento para ir declarando el hilo de la conversión que administrará dicha intención. Así, se puede ir creando un flujo (o árbol) de conversación.
Fulfillment
Creamos un script para conectarnos al calendario:
'use strict';
// Import the Dialogflow module from Google client libraries.
const functions = require('firebase-functions');
const {google} = require('googleapis');
const {WebhookClient} = require('dialogflow-fulfillment');
// Enter your calendar ID below and service account JSON below
const calendarId = "appointment-scheduler@marketshop-362815.iam.gserviceaccount.com";
const serviceAccount = { xxx };
// Set up Google Calendar Service account credentials
const serviceAccountAuth = new google.auth.JWT({
email: serviceAccount.client_email,
key: serviceAccount.private_key,
scopes: 'https://www.googleapis.com/auth/calendar'
});
const calendar = google.calendar('v3');
process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements
const timeZone = 'America/Los_Angeles';
const timeZoneOffset = '-07:00';
// Set the DialogflowApp object to handle the HTTPS POST request.
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log("Parameters", agent.parameters);
const appointment_type = agent.parameters.isapre;
function makeAppointment (agent) {
// Calculate appointment start and end datetimes (end = +1hr from start)
const dateTimeStart = new Date(Date.parse(agent.parameters.date.split('T')[0] + 'T' + agent.parameters.time.split('T')[1].split('-')[0] + timeZoneOffset));
const dateTimeEnd = new Date(new Date(dateTimeStart).setHours(dateTimeStart.getHours() + 1));
const appointmentTimeString = dateTimeStart.toLocaleString(
'en-US',
{ month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone }
);
// Check the availability of the time, and make an appointment if there is time on the calendar
return createCalendarEvent(dateTimeStart, dateTimeEnd, appointment_type).then(() => {
agent.add(`Ok, let me see if we can fit you in. ${appointmentTimeString} is fine!.`);
}).catch(() => {
agent.add(`I'm sorry, there are no slots available for ${appointmentTimeString}.`);
});
}
// Handle the Dialogflow intent named 'Schedule Appointment'.
let intentMap = new Map();
intentMap.set('examen.appointment', makeAppointment);
agent.handleRequest(intentMap);
});
//Creates calendar event in Google Calendar
function createCalendarEvent (dateTimeStart, dateTimeEnd, appointment_type) {
return new Promise((resolve, reject) => {
calendar.events.list({
auth: serviceAccountAuth, // List events for time period
calendarId: calendarId,
timeMin: dateTimeStart.toISOString(),
timeMax: dateTimeEnd.toISOString()
}, (err, calendarResponse) => {
// Check if there is a event already on the Calendar
if (err || calendarResponse.data.items.length > 0) {
reject(err || new Error('Requested time conflicts with another appointment'));
} else {
// Create event for the requested time period
calendar.events.insert({ auth: serviceAccountAuth,
calendarId: calendarId,
resource: {summary: appointment_type +' Appointment', description: appointment_type,
start: {dateTime: dateTimeStart},
end: {dateTime: dateTimeEnd}}
}, (err, event) => {
err ? reject(err) : resolve(event);
}
);
}
});
});
}
WhatApp Bot
Rocketchat también tiene una aplicación que se integra con la API de WhatsApp. Este permite extender las capacidad del Bot a WhatsApp
Video
Aquí una breve demostración de RocketChat con Google DialogFlow y WhatsApp: