Compare commits

..

1 Commits

Author SHA1 Message Date
Leifer
e9ed8e514e update changelog 2022-10-20 14:06:13 +02:00
9 changed files with 97 additions and 142 deletions

View File

@@ -12,3 +12,7 @@
- add support for ubuntu/linux - add support for ubuntu/linux
https://stackoverflow.com/questions/51855169/dialogflow-403-iam-permission-dialogflow-sessions-detectintent https://stackoverflow.com/questions/51855169/dialogflow-403-iam-permission-dialogflow-sessions-detectintent
#### Actualización 20 Oct 2022
- npm update
- use node crypto instead of nanoid

View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2022 Leifer Mendez
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,4 +1,27 @@
## Chatbot Whatsapp (OpenSource) ## Chatbot Whatsapp (OpenSource)
#### Actualizado Abril 2022
El siguiente proyecto se realizó con fines educativos para el canal de [Youtube (Leifer Mendez)](https://www.youtube.com/channel/UCgrIGp5QAnC0J8LfNJxDRDw?sub_confirmation=1) donde aprendemos a crear y implementar un chatbot increíble usando [node.js](https://codigoencasa.com/tag/nodejs/) además le agregamos inteligencia artificial gracias al servicio de __dialogflow__.
[![Video](https://i.giphy.com/media/OBDi3CXC83WkNeLEZP/giphy.webp)](https://youtu.be/5lEMCeWEJ8o)
### ATENCION 🔴
> 💥💥 Si te aparece el Error Multi-device es porque tienes la cuenta de whatsapp afiliada al modo "BETA de Multi dispositivo" por el momento no se tiene soporte para esas personas si tu quieres hacer uso de este __BOT__ debes de salir del modo BETA y intentarlo de la manera tradicional
> El core de whatsapp esta en constante actualizaciones por lo cual siempre revisa la ultima fecha de la actualizacion
> [VER](https://github.com/leifermendez/bot-whatsapp/commits/main)
### Busco colaboradores ⭐
Hola amigos me gusta mucho este proyecto pero por cuestiones de tiempo se me dificulta mantener las actualizaciones si alguno quieres participar en el proyecto escribeme a leifer.contacto@gmail.com
#### Acceso rápido
> Si tienes una cuenta en __heroku__ puedes desplegar este proyecto con (1 click)
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/leifermendez/bot-whatsapp)
> Comprarme un cafe!
[![Comprar](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/leifermendez)
#### Actualización #### Actualización
@@ -58,6 +81,7 @@ await sendMediaVoiceNote(client, from, 'PTT-20220223-WA0000.opus')
## Instruciones ## Instruciones
__Descargar o Clonar repositorio__ __Descargar o Clonar repositorio__
![](https://i.imgur.com/dSpUbFz.png)
__Usas ¿Ubuntu / Linux?__ __Usas ¿Ubuntu / Linux?__
> Asegurate de instalar los siguientes paquetes > Asegurate de instalar los siguientes paquetes
@@ -69,9 +93,9 @@ sudo apt install -y gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups
__Instalar dependencias (npm install)__ __Instalar dependencias (npm install)__
> Ubicate en le directorio que descargaste y via consola o terminal ejecuta el siguiente comando > Ubicate en le directorio que descargaste y via consola o terminal ejecuta el siguiente comando
``` `npm install`
npm i
``` ![](https://i.imgur.com/BJuMjGR.png)
__Configurar .env__ __Configurar .env__
> Con el editor de texto crea un archivo `.env` el cual debes de guiarte del archivo `.env.example` > Con el editor de texto crea un archivo `.env` el cual debes de guiarte del archivo `.env.example`
@@ -90,14 +114,21 @@ SQL_PASS=
SQL_DATABASE= SQL_DATABASE=
``` ```
![](https://i.imgur.com/9poNnW0.png)
__Ejecutar el script__ __Ejecutar el script__
> Ubicate en le directorio que descargaste y via consola o terminal ejecuta el siguiente comando > Ubicate en le directorio que descargaste y via consola o terminal ejecuta el siguiente comando
`npm run start` `npm run start`
![](https://i.imgur.com/eMkBkuJ.png)
__Whatsapp en tu celular__ __Whatsapp en tu celular__
> Ahora abre la aplicación de Whatsapp en tu dispositivo y escanea el código QR > Ahora abre la aplicación de Whatsapp en tu dispositivo y escanea el código QR
<img src="https://i.imgur.com/RSbPtat.png" width="500" /> <img src="https://i.imgur.com/RSbPtat.png" width="500" />
Tambien puedes visitar la pagina http://127.0.0.1:3000/qr Visitar la pagina
`http://localhost:3000/qr`
![](https://i.imgur.com/Q3JEDlP.png)
__Listo 😎__ __Listo 😎__
> Cuando sale este mensaje tu BOT está __listo__ para trabajar! > Cuando sale este mensaje tu BOT está __listo__ para trabajar!
@@ -114,3 +145,11 @@ __Listo 😎__
> Ahora deberías obtener un arespuesta por parte del BOT como la siguiente, ademas de esto tambien se crea un archivo excel > Ahora deberías obtener un arespuesta por parte del BOT como la siguiente, ademas de esto tambien se crea un archivo excel
con el historial de conversación con el número de tu cliente con el historial de conversación con el número de tu cliente
![](https://i.imgur.com/lrMLgR8.png)
![](https://i.imgur.com/UYcoUSV.png)
## Preguntar al BOT
> Puedes interactuar con el bot ejemplo escribele __hola__ y el bot debe responderte!
![](https://i.imgur.com/cNAS51I.png)

View File

@@ -1,6 +1,6 @@
const dialogflow = require('@google-cloud/dialogflow'); const dialogflow = require('@google-cloud/dialogflow');
const fs = require('fs') const fs = require('fs')
const crypto = require('crypto');
/** /**
* Debes de tener tu archivo con el nombre "chatbot-account.json" en la raíz del proyecto * Debes de tener tu archivo con el nombre "chatbot-account.json" en la raíz del proyecto
*/ */
@@ -30,9 +30,9 @@ const checkFileCredentials = () => {
// Detect intent method // Detect intent method
const detectIntent = async (queryText, waPhoneNumber) => { const detectIntent = async (queryText) => {
let media = null; let media = null;
const sessionId = KEEP_DIALOG_FLOW ? 1 : waPhoneNumber; const sessionId = KEEP_DIALOG_FLOW ? 1 : crypto.randomUUID();
const sessionPath = sessionClient.projectAgentSessionPath(PROJECID, sessionId); const sessionPath = sessionClient.projectAgentSessionPath(PROJECID, sessionId);
const languageCode = process.env.LANGUAGE const languageCode = process.env.LANGUAGE
const request = { const request = {
@@ -56,7 +56,7 @@ const detectIntent = async (queryText, waPhoneNumber) => {
const { fields } = parsePayload.payload const { fields } = parsePayload.payload
media = fields.media.stringValue || null media = fields.media.stringValue || null
} }
const customPayload = parsePayload ? parsePayload['payload'] : null const customPayload = parsePayload['payload']
const parseData = { const parseData = {
replyMessage: queryResult.fulfillmentText, replyMessage: queryResult.fulfillmentText,
@@ -66,8 +66,8 @@ const detectIntent = async (queryText, waPhoneNumber) => {
return parseData return parseData
} }
const getDataIa = (message = '', sessionId = '', cb = () => { }) => { const getDataIa = (message = '', cb = () => { }) => {
detectIntent(message, sessionId).then((res) => { detectIntent(message).then((res) => {
cb(res) cb(res)
}) })
} }

View File

@@ -52,13 +52,13 @@ const reply = (step) => new Promise((resolve, reject) => {
} }
}) })
const getIA = (message, sessionId) => new Promise((resolve, reject) => { const getIA = (message) => new Promise((resolve, reject) => {
/** /**
* Si usas dialogflow * Si usas dialogflow
*/ */
if (process.env.DATABASE === 'dialogflow') { if (process.env.DATABASE === 'dialogflow') {
let resData = { replyMessage: '', media: null, trigger: null } let resData = { replyMessage: '', media: null, trigger: null }
getDataIa(message, sessionId, (dt) => { getDataIa(message,(dt) => {
resData = { ...resData, ...dt } resData = { ...resData, ...dt }
resolve(resData) resolve(resData)
}) })

3
app.js
View File

@@ -57,7 +57,7 @@ const listenMessage = () => client.on('message', async msg => {
if (process.env.DATABASE === 'dialogflow') { if (process.env.DATABASE === 'dialogflow') {
if(!message.length) return; if(!message.length) return;
const response = await bothResponse(message, number); const response = await bothResponse(message);
await sendMessage(client, from, response.replyMessage); await sendMessage(client, from, response.replyMessage);
if (response.media) { if (response.media) {
sendMedia(client, from, response.media); sendMedia(client, from, response.media);
@@ -169,3 +169,4 @@ server.listen(port, () => {
console.log(`El server esta listo por el puerto ${port}`); console.log(`El server esta listo por el puerto ${port}`);
}) })
checkEnvFile(); checkEnvFile();

View File

@@ -15,8 +15,8 @@ const responseMessages = async (step) => {
return data return data
} }
const bothResponse = async (message, sessionId) => { const bothResponse = async (message) => {
const data = await getIA(message, sessionId) const data = await getIA(message)
if(data && data.media){ if(data && data.media){
const file = await saveExternalFile(data.media) const file = await saveExternalFile(data.media)
return {...data,...{media:file}} return {...data,...{media:file}}

92
package-lock.json generated
View File

@@ -1,11 +1,11 @@
{ {
"name": "bot-whatsapp", "name": "test-ws-bot",
"version": "1.0.0", "version": "1.0.0",
"lockfileVersion": 2, "lockfileVersion": 2,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "bot-whatsapp", "name": "test-ws-bot",
"version": "1.0.0", "version": "1.0.0",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
@@ -22,7 +22,7 @@
"qrcode-terminal": "^0.12.0", "qrcode-terminal": "^0.12.0",
"socket.io": "^4.5.1", "socket.io": "^4.5.1",
"stormdb": "^0.6.0", "stormdb": "^0.6.0",
"whatsapp-web.js": "^1.18.4", "whatsapp-web.js": "^1.17.1",
"xlsx": "^0.18.5" "xlsx": "^0.18.5"
}, },
"devDependencies": { "devDependencies": {
@@ -30,7 +30,7 @@
"prettier": "2.7.1" "prettier": "2.7.1"
}, },
"engines": { "engines": {
"node": "16.x" "node": "14.x"
} }
}, },
"node_modules/@babel/parser": { "node_modules/@babel/parser": {
@@ -5022,9 +5022,9 @@
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
}, },
"node_modules/whatsapp-web.js": { "node_modules/whatsapp-web.js": {
"version": "1.18.4", "version": "1.17.1",
"resolved": "https://registry.npmjs.org/whatsapp-web.js/-/whatsapp-web.js-1.18.4.tgz", "resolved": "https://registry.npmjs.org/whatsapp-web.js/-/whatsapp-web.js-1.17.1.tgz",
"integrity": "sha512-Dqu6Q37tDDAcVJ44aMdRE76sI/9rBCUG+NTz1Kxh2w4obX2WtpoRetilxqgx1r4+pFUl58Lf21wGOEwPZ1pT/A==", "integrity": "sha512-dr9o+RHHMWX0eJrowtIqHgr3FmXiSktr4aRK6psxEGwD7KXDfgeXTul3fu+qdtX4LAn8p4FtnmN1cc9WFNYWBQ==",
"dependencies": { "dependencies": {
"@pedroslopez/moduleraid": "^5.0.2", "@pedroslopez/moduleraid": "^5.0.2",
"fluent-ffmpeg": "^2.1.2", "fluent-ffmpeg": "^2.1.2",
@@ -5036,37 +5036,6 @@
}, },
"engines": { "engines": {
"node": ">=12.0.0" "node": ">=12.0.0"
},
"optionalDependencies": {
"archiver": "^5.3.1",
"fs-extra": "^10.1.0",
"unzipper": "^0.10.11"
}
},
"node_modules/whatsapp-web.js/node_modules/fs-extra": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
"optional": true,
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/whatsapp-web.js/node_modules/jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"optional": true,
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
} }
}, },
"node_modules/whatsapp-web.js/node_modules/mime": { "node_modules/whatsapp-web.js/node_modules/mime": {
@@ -5080,15 +5049,6 @@
"node": ">=10.0.0" "node": ">=10.0.0"
} }
}, },
"node_modules/whatsapp-web.js/node_modules/universalify": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz",
"integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==",
"optional": true,
"engines": {
"node": ">= 10.0.0"
}
},
"node_modules/whatwg-url": { "node_modules/whatwg-url": {
"version": "5.0.0", "version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
@@ -9167,53 +9127,23 @@
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
}, },
"whatsapp-web.js": { "whatsapp-web.js": {
"version": "1.18.4", "version": "1.17.1",
"resolved": "https://registry.npmjs.org/whatsapp-web.js/-/whatsapp-web.js-1.18.4.tgz", "resolved": "https://registry.npmjs.org/whatsapp-web.js/-/whatsapp-web.js-1.17.1.tgz",
"integrity": "sha512-Dqu6Q37tDDAcVJ44aMdRE76sI/9rBCUG+NTz1Kxh2w4obX2WtpoRetilxqgx1r4+pFUl58Lf21wGOEwPZ1pT/A==", "integrity": "sha512-dr9o+RHHMWX0eJrowtIqHgr3FmXiSktr4aRK6psxEGwD7KXDfgeXTul3fu+qdtX4LAn8p4FtnmN1cc9WFNYWBQ==",
"requires": { "requires": {
"@pedroslopez/moduleraid": "^5.0.2", "@pedroslopez/moduleraid": "^5.0.2",
"archiver": "^5.3.1",
"fluent-ffmpeg": "^2.1.2", "fluent-ffmpeg": "^2.1.2",
"fs-extra": "^10.1.0",
"jsqr": "^1.3.1", "jsqr": "^1.3.1",
"mime": "^3.0.0", "mime": "^3.0.0",
"node-fetch": "^2.6.5", "node-fetch": "^2.6.5",
"node-webpmux": "^3.1.0", "node-webpmux": "^3.1.0",
"puppeteer": "^13.0.0", "puppeteer": "^13.0.0"
"unzipper": "^0.10.11"
}, },
"dependencies": { "dependencies": {
"fs-extra": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
"integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
"optional": true,
"requires": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
}
},
"jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"optional": true,
"requires": {
"graceful-fs": "^4.1.6",
"universalify": "^2.0.0"
}
},
"mime": { "mime": {
"version": "3.0.0", "version": "3.0.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",
"integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==" "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A=="
},
"universalify": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz",
"integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==",
"optional": true
} }
} }
}, },

View File

@@ -12,6 +12,7 @@
"bot-whatsapp", "bot-whatsapp",
"node-bot-whatsapp" "node-bot-whatsapp"
], ],
"contributors": [ "contributors": [
{ {
"email": "leifer33@gmail.com", "email": "leifer33@gmail.com",
@@ -43,7 +44,7 @@
"qrcode-terminal": "^0.12.0", "qrcode-terminal": "^0.12.0",
"socket.io": "^4.5.1", "socket.io": "^4.5.1",
"stormdb": "^0.6.0", "stormdb": "^0.6.0",
"whatsapp-web.js": "^1.18.4", "whatsapp-web.js": "^1.17.1",
"xlsx": "^0.18.5" "xlsx": "^0.18.5"
}, },
"devDependencies": { "devDependencies": {
@@ -54,3 +55,4 @@
"node": "16.x" "node": "16.x"
} }
} }