Skip to content

Commit

Permalink
feat(provider): 🐛 dialogflow
Browse files Browse the repository at this point in the history
  • Loading branch information
leifermendez committed Dec 16, 2022
1 parent a52aaa1 commit 4ec6f1e
Show file tree
Hide file tree
Showing 11 changed files with 228 additions and 10 deletions.
2 changes: 1 addition & 1 deletion GLOSSARY.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
CTX: Es el objeto que representa un mensaje, con opciones, id, ref
messageInComming: Objeto entrante del provider {body, from,...}
messageInComming: Objeto entrante del provider {body, from,to,...}
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@
"create-bot:rollup": "rollup --config ./packages/create-bot-whatsapp/rollup-create.config.js ",
"bot:rollup": "rollup --config ./packages/bot/rollup-bot.config.js",
"provider:rollup": "rollup --config ./packages/provider/rollup-provider.config.js ",
"contexts:rollup": "rollup --config ./packages/contexts/rollup-contexts.config.js",
"database:rollup": "rollup --config ./packages/database/rollup-database.config.js",
"create-bot-whatsapp:rollup": "rollup --config ./packages/create-bot-whatsapp/rollup-create.config.js",
"format:check": "prettier --check ./packages",
"format:write": "prettier --write ./packages",
"fmt.staged": "pretty-quick --staged",
"lint:check": "eslint ./packages",
"lint:fix": "eslint --fix ./packages",
"build": "yarn run cli:rollup && yarn run bot:rollup && yarn run provider:rollup && yarn run database:rollup && yarn run create-bot-whatsapp:rollup",
"build": "yarn run cli:rollup && yarn run bot:rollup && yarn run provider:rollup && yarn run database:rollup && yarn run contexts:rollup && yarn run create-bot-whatsapp:rollup",
"copy.lib": "node ./scripts/move.js",
"test.unit": "node ./node_modules/uvu/bin.js packages test",
"test.coverage": "node ./node_modules/c8/bin/c8.js npm run test.unit",
Expand All @@ -37,6 +38,7 @@
"packages/cli",
"packages/database",
"packages/provider",
"packages/contexts",
"packages/docs"
],
"keywords": [
Expand Down
19 changes: 11 additions & 8 deletions packages/bot/core/core.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ class CoreClass {
]

/**
*
* @param {*} messageInComming
* GLOSSARY.md
* @param {*} messageCtxInComming
* @returns
*/
handleMsg = async (messageInComming) => {
logger.log(`[handleMsg]: `, messageInComming)
const { body, from } = messageInComming
handleMsg = async (messageCtxInComming) => {
logger.log(`[handleMsg]: `, messageCtxInComming)
const { body, from } = messageCtxInComming
let msgToSend = []
let fallBackFlag = false

Expand Down Expand Up @@ -95,9 +95,12 @@ class CoreClass {
// 📄 [options: callback]: Si se tiene un callback se ejecuta
if (!fallBackFlag && refToContinue && prevMsg?.options?.callback) {
const indexFlow = this.flowClass.findIndexByRef(refToContinue?.ref)
this.flowClass.allCallbacks[indexFlow].callback(messageInComming, {
fallBack,
})
this.flowClass.allCallbacks[indexFlow].callback(
messageCtxInComming,
{
fallBack,
}
)
}

// 📄🤘(tiene return) [options: nested(array)]: Si se tiene flujos hijos los implementa
Expand Down
16 changes: 16 additions & 0 deletions packages/contexts/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "@bot-whatsapp/contexts",
"version": "0.0.1",
"description": "",
"main": "./lib/bundle.contexts.cjs",
"files": [
"./lib/"
],
"exports": {
"./mock": "./lib/mock/index.cjs",
"./dialogflow": "./lib/dialogflow/index.cjs"
},
"dependencies": {
"@bot-whatsapp/bot": "*"
}
}
24 changes: 24 additions & 0 deletions packages/contexts/rollup-contexts.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const banner = require('../../config/banner.rollup.json')
const commonjs = require('@rollup/plugin-commonjs')
const { join } = require('path')

module.exports = [
{
input: join(__dirname, 'src', 'mock', 'index.js'),
output: {
banner: banner['banner.output'].join(''),
file: join(__dirname, 'lib', 'mock', 'index.cjs'),
format: 'cjs',
},
plugins: [commonjs()],
},
{
input: join(__dirname, 'src', 'dialogflow', 'index.js'),
output: {
banner: banner['banner.output'].join(''),
file: join(__dirname, 'lib', 'dialogflow', 'index.cjs'),
format: 'cjs',
},
plugins: [commonjs()],
},
]
112 changes: 112 additions & 0 deletions packages/contexts/src/dialogflow/dialogflow.class.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
const { CoreClass } = require('@bot-whatsapp/bot')
const dialogflow = require('@google-cloud/dialogflow')
const { existsSync, readFileSync } = require('fs')
const { join } = require('path')

/**
* Necesita extender de core.class
* handleMsg(messageInComming) // const { body, from } = messageInComming
*/

const GOOGLE_ACCOUNT_PATH = join(process.cwd(), 'google-key.json')

class DialogFlowContext extends CoreClass {
projectId = null
configuration = null
sessionClient = null

constructor(_database, _provider) {
super(null, _database, _provider)
}

/**
* Verificar conexión con servicio de DialogFlow
*/
init = () => {
if (!existsSync(GOOGLE_ACCOUNT_PATH)) {
/**
* Emitir evento de error para que se mueste por consola dicinedo que no tiene el json
* */
}

const rawJson = readFileSync(GOOGLE_ACCOUNT_PATH, 'utf-8')
const { project_id, private_key, client_email } = JSON.parse(rawJson)

this.projectId = project_id
this.configuration = {
credentials: {
private_key,
client_email,
},
}

this.sessionClient = new dialogflow.SessionsClient(this.configuration)
}

/**
* GLOSSARY.md
* @param {*} messageCtxInComming
* @returns
*/
handleMsg = async (messageCtxInComming) => {
const languageCode = process.env.LANGUAGE || 'es' //????? language

console.log('DEBUG:', messageCtxInComming)
const { from, body } = messageCtxInComming // body: hola
let media = null

/**
* 📄 Creamos session de contexto basado en el numero de la persona
* para evitar este problema.
* https://github.com/codigoencasa/bot-whatsapp/pull/140
*/
const session = this.sessionClient.projectAgentSessionPath(
this.projectId,
from
)
const requestDialog = {
session,
queryInput: {
text: {
text: body,
languageCode,
},
},
}

const [singleResponse] = (await sessionClient.detectIntent(
requestDialog
)) || [null]

const { queryResult } = singleResponse
const { intent } = queryResult || { intent: {} }

// const parseIntent = intent['displayName'] || null
//****** HE LLEGADO A ESTE PUNTO */
//****** this.sendFlow(msgToSend, from) */

const parsePayload = queryResult['fulfillmentMessages'].find(
(a) => a.message === 'payload'
)
// console.log(singleResponse)
if (parsePayload && parsePayload.payload) {
const { fields } = parsePayload.payload
media = fields.media.stringValue || null
}
const customPayload = parsePayload ? parsePayload['payload'] : null

const parseData = {
replyMessage: queryResult.fulfillmentText,
media,
trigger: null,
}

// se tiene que enviar mensaje
// msgToSend = [{options?.delay}]
this.sendFlow(msgToSend, from)

return parseData
}
}

module.exports = DialogFlowContext
14 changes: 14 additions & 0 deletions packages/contexts/src/dialogflow/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const DialogFlowClass = require('./dialogflow.class')

/**
* Crear instancia de clase Bot
* @param {*} args
* @returns
*/
const createBotDialog = async ({ flow, database, provider }) =>
new DialogFlowClass(flow, database, provider)

module.exports = {
createBotDialog,
DialogFlowClass,
}
14 changes: 14 additions & 0 deletions packages/contexts/src/mock/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const MockClass = require('./mock.class')

/**
* Crear instancia de clase Bot
* @param {*} args
* @returns
*/
const createBotMock = async ({ database, provider }) =>
new MockClass(database, provider)

module.exports = {
createBotMock,
MockClass,
}
24 changes: 24 additions & 0 deletions packages/contexts/src/mock/mock.class.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const { CoreClass } = require('@bot-whatsapp/bot')
/**
* Necesita extender de core.class
* handleMsg(messageInComming) // const { body, from } = messageInComming
*/

class MockContext extends CoreClass {
constructor(_database, _provider) {
super(null, _database, _provider)
}

init = () => {}

/**
* GLOSSARY.md
* @param {*} messageCtxInComming
* @returns
*/
handleMsg = async ({ from, body }) => {
console.log('DEBUG:', messageCtxInComming)
}
}

module.exports = MockContext
1 change: 1 addition & 0 deletions scripts/move.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ Promise.all([
copyLibPkg('bot', appDir),
copyLibPkg('database', appDir),
copyLibPkg('provider', appDir),
copyLibPkg('contexts', appDir),
]).then(() => console.log('Todas las librerías copiadas'))
8 changes: 8 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -963,6 +963,14 @@ __metadata:
languageName: unknown
linkType: soft

"@bot-whatsapp/contexts@workspace:packages/contexts":
version: 0.0.0-use.local
resolution: "@bot-whatsapp/contexts@workspace:packages/contexts"
dependencies:
"@bot-whatsapp/bot": "*"
languageName: unknown
linkType: soft

"@bot-whatsapp/database@npm:*":
version: 0.1.2
resolution: "@bot-whatsapp/database@npm:0.1.2"
Expand Down

0 comments on commit 4ec6f1e

Please sign in to comment.