mirror of
https://github.com/cheveguerra/bot-whatsapp.git
synced 2026-04-17 19:26:23 +00:00
feat(provider): 🐛 dialogflow
This commit is contained in:
@@ -1,2 +1,2 @@
|
|||||||
CTX: Es el objeto que representa un mensaje, con opciones, id, ref
|
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,...}
|
||||||
@@ -10,6 +10,7 @@
|
|||||||
"create-bot:rollup": "rollup --config ./packages/create-bot-whatsapp/rollup-create.config.js ",
|
"create-bot:rollup": "rollup --config ./packages/create-bot-whatsapp/rollup-create.config.js ",
|
||||||
"bot:rollup": "rollup --config ./packages/bot/rollup-bot.config.js",
|
"bot:rollup": "rollup --config ./packages/bot/rollup-bot.config.js",
|
||||||
"provider:rollup": "rollup --config ./packages/provider/rollup-provider.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",
|
"database:rollup": "rollup --config ./packages/database/rollup-database.config.js",
|
||||||
"create-bot-whatsapp:rollup": "rollup --config ./packages/create-bot-whatsapp/rollup-create.config.js",
|
"create-bot-whatsapp:rollup": "rollup --config ./packages/create-bot-whatsapp/rollup-create.config.js",
|
||||||
"format:check": "prettier --check ./packages",
|
"format:check": "prettier --check ./packages",
|
||||||
@@ -17,7 +18,7 @@
|
|||||||
"fmt.staged": "pretty-quick --staged",
|
"fmt.staged": "pretty-quick --staged",
|
||||||
"lint:check": "eslint ./packages",
|
"lint:check": "eslint ./packages",
|
||||||
"lint:fix": "eslint --fix ./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",
|
"copy.lib": "node ./scripts/move.js",
|
||||||
"test.unit": "node ./node_modules/uvu/bin.js packages test",
|
"test.unit": "node ./node_modules/uvu/bin.js packages test",
|
||||||
"test.coverage": "node ./node_modules/c8/bin/c8.js npm run test.unit",
|
"test.coverage": "node ./node_modules/c8/bin/c8.js npm run test.unit",
|
||||||
@@ -37,6 +38,7 @@
|
|||||||
"packages/cli",
|
"packages/cli",
|
||||||
"packages/database",
|
"packages/database",
|
||||||
"packages/provider",
|
"packages/provider",
|
||||||
|
"packages/contexts",
|
||||||
"packages/docs"
|
"packages/docs"
|
||||||
],
|
],
|
||||||
"keywords": [
|
"keywords": [
|
||||||
|
|||||||
@@ -58,13 +58,13 @@ class CoreClass {
|
|||||||
]
|
]
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
* GLOSSARY.md
|
||||||
* @param {*} messageInComming
|
* @param {*} messageCtxInComming
|
||||||
* @returns
|
* @returns
|
||||||
*/
|
*/
|
||||||
handleMsg = async (messageInComming) => {
|
handleMsg = async (messageCtxInComming) => {
|
||||||
logger.log(`[handleMsg]: `, messageInComming)
|
logger.log(`[handleMsg]: `, messageCtxInComming)
|
||||||
const { body, from } = messageInComming
|
const { body, from } = messageCtxInComming
|
||||||
let msgToSend = []
|
let msgToSend = []
|
||||||
let fallBackFlag = false
|
let fallBackFlag = false
|
||||||
|
|
||||||
@@ -95,9 +95,12 @@ class CoreClass {
|
|||||||
// 📄 [options: callback]: Si se tiene un callback se ejecuta
|
// 📄 [options: callback]: Si se tiene un callback se ejecuta
|
||||||
if (!fallBackFlag && refToContinue && prevMsg?.options?.callback) {
|
if (!fallBackFlag && refToContinue && prevMsg?.options?.callback) {
|
||||||
const indexFlow = this.flowClass.findIndexByRef(refToContinue?.ref)
|
const indexFlow = this.flowClass.findIndexByRef(refToContinue?.ref)
|
||||||
this.flowClass.allCallbacks[indexFlow].callback(messageInComming, {
|
this.flowClass.allCallbacks[indexFlow].callback(
|
||||||
fallBack,
|
messageCtxInComming,
|
||||||
})
|
{
|
||||||
|
fallBack,
|
||||||
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 📄🤘(tiene return) [options: nested(array)]: Si se tiene flujos hijos los implementa
|
// 📄🤘(tiene return) [options: nested(array)]: Si se tiene flujos hijos los implementa
|
||||||
|
|||||||
16
packages/contexts/package.json
Normal file
16
packages/contexts/package.json
Normal file
@@ -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
packages/contexts/rollup-contexts.config.js
Normal file
24
packages/contexts/rollup-contexts.config.js
Normal file
@@ -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
packages/contexts/src/dialogflow/dialogflow.class.js
Normal file
112
packages/contexts/src/dialogflow/dialogflow.class.js
Normal file
@@ -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
packages/contexts/src/dialogflow/index.js
Normal file
14
packages/contexts/src/dialogflow/index.js
Normal file
@@ -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
packages/contexts/src/mock/index.js
Normal file
14
packages/contexts/src/mock/index.js
Normal file
@@ -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
packages/contexts/src/mock/mock.class.js
Normal file
24
packages/contexts/src/mock/mock.class.js
Normal file
@@ -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
|
||||||
@@ -15,4 +15,5 @@ Promise.all([
|
|||||||
copyLibPkg('bot', appDir),
|
copyLibPkg('bot', appDir),
|
||||||
copyLibPkg('database', appDir),
|
copyLibPkg('database', appDir),
|
||||||
copyLibPkg('provider', appDir),
|
copyLibPkg('provider', appDir),
|
||||||
|
copyLibPkg('contexts', appDir),
|
||||||
]).then(() => console.log('Todas las librerías copiadas'))
|
]).then(() => console.log('Todas las librerías copiadas'))
|
||||||
|
|||||||
@@ -963,6 +963,14 @@ __metadata:
|
|||||||
languageName: unknown
|
languageName: unknown
|
||||||
linkType: soft
|
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:*":
|
"@bot-whatsapp/database@npm:*":
|
||||||
version: 0.1.2
|
version: 0.1.2
|
||||||
resolution: "@bot-whatsapp/database@npm:0.1.2"
|
resolution: "@bot-whatsapp/database@npm:0.1.2"
|
||||||
|
|||||||
Reference in New Issue
Block a user