🫡[Done!] thanks everyone for this awesome job

🫡[Done!] thanks everyone for this awesome job
This commit is contained in:
Leifer Mendez
2023-01-05 15:01:59 +01:00
committed by GitHub
345 changed files with 34024 additions and 11191 deletions

8
.c8rc.json Normal file
View File

@@ -0,0 +1,8 @@
{
"src": "./src",
"exclude": ["**/bot/lib", "__mocks__", "**/mock"],
"reporter": ["html"],
"report-dir": "./coverage",
"check-coverage": true,
"lines": 90
}

View File

@@ -1,15 +0,0 @@
######DATABASE: none, mysql, dialogflow
DEFAULT_MESSAGE=true
SAVE_MEDIA=true
PORT=3000
DATABASE=none
LANGUAGE=es
SQL_HOST=
SQL_USER=
SQL_PASS=
SQL_DATABASE=
KEEP_DIALOG_FLOW=false
MULTI_DEVICE=true
DIALOGFLOW_MEDIA_FOR_SLOT_FILLING=false
GDRIVE_FOLDER_ID=

1
.eslintignore Normal file
View File

@@ -0,0 +1 @@
packages/docs/*

18
.eslintrc.js Normal file
View File

@@ -0,0 +1,18 @@
module.exports = {
env: {
browser: true,
commonjs: true,
es2021: true,
node: true,
},
extends: 'eslint:recommended',
overrides: [],
parserOptions: {
ecmaVersion: 'latest',
},
rules: {
'no-unsafe-negation': 'off',
'no-prototype-builtins': 'off',
'no-useless-escape': 'off',
},
}

5
.github/FUNDING.yml vendored
View File

@@ -1,3 +1,4 @@
patreon: leifermendez
custom: "https://www.buymeacoffee.com/leifermendez"
# These are supported funding model platforms
open_collective: bot-whatsapp
patreon: leifermendez
custom: https://www.buymeacoffee.com/leifermendez

View File

@@ -1,58 +1,58 @@
name: 🐛 Reporte Bug
name: 🐛 Reporte Bug
description: Algo no va bien?. Hazlo saber
labels: [bug, triage]
title: '[🐛]'
body:
- type: markdown
attributes:
value: |
Gracias por tomarte el tiempo de reportar este problema
- type: dropdown
id: version
attributes:
label: ¿Que versión estas usando?
description: '__INFO:__ Recuerda que puedes consultar dudas directamente en [discord](https://link.codigoencasa.com/DISCORD)'
options:
- v2
- v1
validations:
required: true
- type: markdown
attributes:
value: |
Gracias por tomarte el tiempo de reportar este problema
- type: dropdown
id: component
attributes:
label: ¿Sobre que afecta?
options:
- Flujo de palabras (Flow)
- DialogFlow
- Base de datos
- Otro
validations:
required: true
- type: dropdown
id: version
attributes:
label: ¿Que versión estas usando?
description: '__INFO:__ Recuerda que puedes consultar dudas directamente en [discord](https://link.codigoencasa.com/DISCORD)'
options:
- v2
- v1
validations:
required: true
- type: textarea
id: description
attributes:
description: 'Trata de ser lo más claro posible, de esa manera podemos entender el contexto de tu problema y darte una mejor solución'
label: Describe tu problema
placeholder: Yo tengo un problema....
- type: dropdown
id: component
attributes:
label: ¿Sobre que afecta?
options:
- Flujo de palabras (Flow)
- DialogFlow
- Base de datos
- Otro
validations:
required: true
validations:
required: true
- type: textarea
id: description
attributes:
description: 'Trata de ser lo más claro posible, de esa manera podemos entender el contexto de tu problema y darte una mejor solución'
label: Describe tu problema
placeholder: Yo tengo un problema....
- type: input
id: reproduction
attributes:
label: Reproducir error
description: __(Recomendación)__ trata de grabar un video puedes usar algunas de las siguientes herramientas [https://www.vidyard.com/](https://www.vidyard.com/) [https://www.loom.com/](https://www.loom.com/) y en lo posbile apoyate en [https://stackblitz.com/](https://stackblitz.com/) para compartir el código de ser necesario
placeholder: URL video o stackblitz
validations:
required: false
validations:
required: true
- type: textarea
id: additional_information
attributes:
label: Información Adicional
validations:
required: false
- type: input
id: reproduction
attributes:
label: Reproducir error
description: __(Recomendación)__ trata de grabar un video puedes usar algunas de las siguientes herramientas [https://www.vidyard.com/](https://www.vidyard.com/) [https://www.loom.com/](https://www.loom.com/) y en lo posbile apoyate en [https://stackblitz.com/](https://stackblitz.com/) para compartir el código de ser necesario
placeholder: URL video o stackblitz
validations:
required: false
- type: textarea
id: additional_information
attributes:
label: Información Adicional
validations:
required: false

View File

@@ -1,4 +1,4 @@
contact_links:
- name: 🤔 Core Team
url: https://link.codigoencasa.com/DISCORD
about: Si quieres formar parte del CoreTeam, patrocinar el proyecto o propuesta profesionales
- name: 🤔 Core Team
url: https://link.codigoencasa.com/DISCORD
about: Si quieres formar parte del CoreTeam, patrocinar el proyecto o propuesta profesionales

View File

@@ -1,79 +1,79 @@
name: 🐬 Caso de uso
name: 🐬 Caso de uso
description: Reporta tu caso de uso y cuales fueron tus resultados
labels: [usecase]
title: '[🐬]'
body:
- type: markdown
attributes:
value: |
Gracias por tomarte el tiempo de detallar este caso de uso, sera de gran utilidad para mantener un software de calidad puedes comenzar
⚡ `npm create bot-whatsapp@dev`
- type: dropdown
id: version
attributes:
label: ¿Cual proveedor usaste?
description: 'Actualmente tenemos varios proveedores que sirven como punto de entrada y salida con Whatsapp'
options:
- whatsapp-web.js
- venom
- bailey
- twilio
- meta
validations:
required: true
- type: markdown
attributes:
value: |
Gracias por tomarte el tiempo de detallar este caso de uso, sera de gran utilidad para mantener un software de calidad puedes comenzar
⚡ `npm create bot-whatsapp@dev`
- type: dropdown
id: component
attributes:
label: ¿Cual base de datos usaste?
options:
- memory
- mongo
- mysql
- json
validations:
required: true
- type: dropdown
id: result
attributes:
label: Conclusion de la prueba
options:
- muy buena
- buena
- tiene errores
validations:
required: true
- type: dropdown
id: version
attributes:
label: ¿Cual proveedor usaste?
description: 'Actualmente tenemos varios proveedores que sirven como punto de entrada y salida con Whatsapp'
options:
- whatsapp-web.js
- venom
- bailey
- twilio
- meta
validations:
required: true
- type: textarea
id: description
attributes:
description: 'Trata de ser lo más claro posible, de esa manera podemos entender el contexto del caso de uso'
label: Describe tu caso
placeholder: Yo tengo un caso....
validations:
required: true
- type: textarea
id: logs
attributes:
label: ¿Logs Importantes?
description: Si tienes algunos logs importantes a tener en cuenta o que muetren algun error en concreto.
render: shell
- type: textarea
id: additional_information
attributes:
label: Información Adicional
validations:
required: false
- type: input
id: usernames
attributes:
label: ¿Quieres que te mencionemos?
description: Siempre buscamos fomentar la comunidad por lo cual si quieres que te mencionemos publicamente en nuestras redes sociales puedes dejar tu username
placeholder: twitter o github o instagram o alguna url
validations:
required: false
- type: dropdown
id: component
attributes:
label: ¿Cual base de datos usaste?
options:
- memory
- mongo
- mysql
- json
validations:
required: true
- type: dropdown
id: result
attributes:
label: Conclusion de la prueba
options:
- muy buena
- buena
- tiene errores
validations:
required: true
- type: textarea
id: description
attributes:
description: 'Trata de ser lo más claro posible, de esa manera podemos entender el contexto del caso de uso'
label: Describe tu caso
placeholder: Yo tengo un caso....
validations:
required: true
- type: textarea
id: logs
attributes:
label: ¿Logs Importantes?
description: Si tienes algunos logs importantes a tener en cuenta o que muetren algun error en concreto.
render: shell
- type: textarea
id: additional_information
attributes:
label: Información Adicional
validations:
required: false
- type: input
id: usernames
attributes:
label: ¿Quieres que te mencionemos?
description: Siempre buscamos fomentar la comunidad por lo cual si quieres que te mencionemos publicamente en nuestras redes sociales puedes dejar tu username
placeholder: twitter o github o instagram o alguna url
validations:
required: false

View File

@@ -0,0 +1,44 @@
name: Rev Major Providers
on:
schedule:
- cron: '0 9 * * *'
jobs:
check-npm:
name: Install Dependencies
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16.x
cache: 'yarn'
registry-url: https://registry.npmjs.org/
- run: corepack enable
- name: Install NPM Dependencies
run: yarn install --immutable --network-timeout 300000
- name: Check Baileys
run: yarn node ./scripts/checker.js --name=baileys --stable=false
- name: Check Venom
run: yarn node ./scripts/checker.js --name=venom --stable=false
- name: Check web-whatsapp
run: yarn node ./scripts/checker.js --name=web-whatsapp --stable=false
- name: Check Meta
run: yarn node ./scripts/checker.js --name=meta --stable=false
- name: Check Twilio
run: yarn node ./scripts/checker.js --name=twilio --stable=false
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: 'ci(providers): 🚩 Check BREAKING CHANGE'

48
.github/workflows/check-providers.yml vendored Normal file
View File

@@ -0,0 +1,48 @@
name: Rev Providers
on:
push:
branches:
- dev
pull_request:
branches:
- dev
jobs:
check-npm:
name: Install Dependencies
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16.x
cache: 'yarn'
registry-url: https://registry.npmjs.org/
- run: corepack enable
- name: Install NPM Dependencies
run: yarn install --immutable --network-timeout 300000
- name: Check Baileys
run: yarn node ./scripts/checker.js --name=baileys --stable=true
- name: Check Venom
run: yarn node ./scripts/checker.js --name=venom --stable=true
- name: Check web-whatsapp
run: yarn node ./scripts/checker.js --name=web-whatsapp --stable=true
- name: Check Meta
run: yarn node ./scripts/checker.js --name=meta --stable=true
- name: Check Twilio
run: yarn node ./scripts/checker.js --name=twilio --stable=true
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: 'ci(providers): 👍 updated versions stable providers'

61
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,61 @@
name: Build and Test
on:
push:
branches:
- dev
pull_request:
branches:
- dev
jobs:
############ BUILD PACKAGE ############
build-package:
name: Build Package
runs-on: ubuntu-latest
needs:
- test-unit
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16.x
cache: 'yarn'
registry-url: https://registry.npmjs.org/
- run: corepack enable
- name: Install NPM Dependencies
run: yarn install --immutable --network-timeout 300000
- name: Build Package
run: yarn build
- name: Build Eslint rules
run: yarn lint:fix
############ UNIT TEST ############
test-unit:
name: Unit Tests
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16.x
cache: 'yarn'
registry-url: https://registry.npmjs.org/
- run: corepack enable
- name: Install NPM Dependencies
run: yarn install --immutable --network-timeout 300000
- name: Unit Tests
run: yarn test

View File

@@ -9,68 +9,67 @@
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
name: 'CodeQL'
on:
push:
branches: [ "main", dev, next-release ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ "main" ]
schedule:
- cron: '21 16 * * 5'
push:
branches: ['main', dev, next-release]
pull_request:
# The branches below must be a subset of the branches above
branches: ['main']
schedule:
- cron: '21 16 * * 5'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Use only 'java' to analyze code written in Java, Kotlin or both
# Use only 'javascript' to analyze code written in JavaScript, TypeScript or both
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
strategy:
fail-fast: false
matrix:
language: ['javascript']
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Use only 'java' to analyze code written in Java, Kotlin or both
# Use only 'javascript' to analyze code written in JavaScript, TypeScript or both
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
steps:
- name: Checkout repository
uses: actions/checkout@v3
steps:
- name: Checkout repository
uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{matrix.language}}"
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: '/language:${{matrix.language}}'

19
.github/workflows/contributors.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
name: Revisando Colaboradores
on:
pull_request:
branches:
- dev
- main
types: [closed]
jobs:
contrib-readme-job:
runs-on: ubuntu-latest
name: A job to automate contrib in readme
steps:
- name: Contribute List
uses: akhilmhdh/contributors-readme-action@v2.3.6
with:
image_size: 50
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

46
.github/workflows/netlify-dev.yml vendored Normal file
View File

@@ -0,0 +1,46 @@
name: 📄 Desplegando documentacion
on:
pull_request:
branches:
- 'feat/docs-**'
- 'fix/docs-**'
push:
branches:
- 'feat/docs-**'
- 'fix/docs-**'
jobs:
############ DOCUMENTATION BUILD ############
build-documentation:
name: Build Package
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16.x
cache: 'yarn'
registry-url: https://registry.npmjs.org/
- run: corepack enable
- name: Install NPM Dependencies
run: yarn install --immutable --network-timeout 300000
- name: Add netlify
run: yarn add netlify-cli -D
- name: Create .env build file
run: |
touch packages/docs/.env
echo VITE_GITHUB_TOKEN=${{ secrets.COLLABORATORS_TOKEN }} >> packages/docs/.env
- name: Build and Deploy
run: |
cd packages/docs
netlify deploy --build --site ${{ secrets.NETLIFY_SITE_ID }} --auth ${{ secrets.NETLIFY_AUTH_TOKEN }}

41
.github/workflows/netlify.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: 📄 (PROD) Desplegando documentacion
on:
push:
branches:
- next-release
jobs:
############ DOCUMENTATION BUILD ############
build-documentation:
name: Build Package
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16.x
cache: 'yarn'
registry-url: https://registry.npmjs.org/
- run: corepack enable
- name: Install NPM Dependencies
run: yarn install --immutable --network-timeout 300000
- name: Add netlify
run: yarn add netlify-cli -D
- name: Create .env build file
run: |
touch packages/docs/.env
echo VITE_GITHUB_TOKEN=${{ secrets.COLLABORATORS_TOKEN }} >> packages/docs/.env
- name: Build and Deploy
run: |
cd packages/docs
netlify deploy --prod --build --site ${{ secrets.NETLIFY_SITE_ID }} --auth ${{ secrets.NETLIFY_AUTH_TOKEN }}

51
.github/workflows/releases-dev.yml vendored Normal file
View File

@@ -0,0 +1,51 @@
name: 🚀 (DEV) Liberando versiones
on:
push:
branches:
- next-release
jobs:
############ RELEASE ############
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16.x
cache: 'yarn'
registry-url: https://registry.npmjs.org/
- run: corepack enable
- name: Install NPM Dependencies
run: yarn install --immutable --network-timeout 300000
- name: Build Package
run: yarn build
- name: Release @bot-whatsapp/bot
run: yarn node ./scripts/release.js --name=bot --version= --token="${{ secrets.NPM_TOKEN }}"
- name: Release @bot-whatsapp/cli
run: yarn node ./scripts/release.js --name=cli --version= --token="${{ secrets.NPM_TOKEN }}"
- name: Release @bot-whatsapp/create-bot-whatsapp
run: yarn node ./scripts/release.js --name=create-bot-whatsapp --version= --token="${{ secrets.NPM_TOKEN }}"
- name: Release @bot-whatsapp/database
run: yarn node ./scripts/release.js --name=database --version= --token="${{ secrets.NPM_TOKEN }}"
- name: Release @bot-whatsapp/provider
run: yarn node ./scripts/release.js --name=provider --version= --token="${{ secrets.NPM_TOKEN }}"
- name: Commit Versioning & Push changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: 'ci(version): :zap: automatic - "${date}" updated versions every packages'
branch: dev

55
.github/workflows/releases.yml vendored Normal file
View File

@@ -0,0 +1,55 @@
name: 🚀⚡ Liberando versiones
on:
push:
tags:
- 'v*.*.*'
jobs:
############ RELEASE ############
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Set output
id: vars
run: echo "tag=${GITHUB_REF#refs/*/}" >> $GITHUB_OUTPUT
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 16.x
cache: 'yarn'
registry-url: https://registry.npmjs.org/
- run: corepack enable
- name: Install NPM Dependencies
run: yarn install --immutable --network-timeout 300000
- name: Build Package
run: yarn build
- name: Release @bot-whatsapp/bot
run: yarn node ./scripts/release.js --name=bot --version="${{ steps.vars.outputs.tag }}" --token="${{ secrets.NPM_TOKEN }}"
- name: Release @bot-whatsapp/cli
run: yarn node ./scripts/release.js --name=cli --version="${{ steps.vars.outputs.tag }}" --token="${{ secrets.NPM_TOKEN }}"
- name: Release @bot-whatsapp/create-bot-whatsapp
run: yarn node ./scripts/release.js --name=create-bot-whatsapp --version="${{ steps.vars.outputs.tag }}" --token="${{ secrets.NPM_TOKEN }}"
- name: Release @bot-whatsapp/database
run: yarn node ./scripts/release.js --name=database --version="${{ steps.vars.outputs.tag }}" --token="${{ secrets.NPM_TOKEN }}"
- name: Release @bot-whatsapp/provider
run: yarn node ./scripts/release.js --name=provider --version="${{ steps.vars.outputs.tag }}" --token="${{ secrets.NPM_TOKEN }}"
- name: Commit Versioning & Push changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: 'release(version): 🚀 - "${{ steps.vars.outputs.tag }}" release'
branch: dev

View File

@@ -6,23 +6,22 @@
name: Revisar ISSUES abandonadas
on:
schedule:
- cron: '55 22 * * *'
schedule:
- cron: '55 22 * * *'
jobs:
stale:
stale:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v5
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: '¿Alguna novedad sobre esta ISSUE?'
stale-pr-message: '¿Alguna novedad sobre esta PULL REQUEST?'
stale-issue-label: 'no-issue-activity'
stale-pr-label: 'no-pr-activity'
exempt-issue-assignees: 'leifermendez'
steps:
- uses: actions/stale@v5
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
stale-issue-message: '¿Alguna novedad sobre esta ISSUE?'
stale-pr-message: '¿Alguna novedad sobre esta PULL REQUEST?'
stale-issue-label: 'no-issue-activity'
stale-pr-label: 'no-pr-activity'
exempt-issue-assignees: 'leifermendez'

32
.gitignore vendored
View File

@@ -1,5 +1,9 @@
/node_modules
/node_modules/*
/packages/*/starters
/packages/*/node_modules
/packages/*/dist
/packages/*/docs/dist
/packages/provider/src/venom/tokens
session.json
chats/*
!chats/.gitkeep
@@ -10,5 +14,27 @@ mediaSend/*
!mediaSend/nota-de-voz.mp3
.env
.wwebjs_auth
backup
backup/*
packages/cli/config.json
config.json
.yarnrc.yml
coverage/
*.lcov
log
log/*
*.log
*.tgz
lib
tmp/
.yarn/*
!.yarn/releases
!.yarn/plugins/@yarnpkg/plugin-postinstall.cjs
.fleet/
example-app*/
base-*/
!starters/apps/base-*/
qr.svg
package-lock.json
yarn-error.log
.npmrc
# Local Netlify folder
.netlify

4
.husky/commit-msg Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx --no -- commitlint --edit

4
.husky/pre-commit Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
yarn run fmt.staged

4
.husky/pre-push Executable file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npm run test

9
.prettierignore Normal file
View File

@@ -0,0 +1,9 @@
packages/**/lib
packages/docs/*.json
**/.git
**/.svn
**/.hg
**/node_modules
*.mjs
*.cjs
*.md

View File

@@ -1 +1,6 @@
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
}

24
.vscode/bot.code-snippets vendored Normal file
View File

@@ -0,0 +1,24 @@
{
"Flow Bot (simple)": {
"scope": "javascript",
"prefix": "bot:flow",
"description": "Crear un flujo simple",
"body": [
"export const flow${1} = addKeyword(['hola', 'buenas'])",
" .addAnswer('Hola! 🚀 Bienvenido a este CHATBOT')",
" .addAnswer('¿Como puedo ayudarte?')"
]
},
"Flow Bot (completo)": {
"scope": "javascript",
"prefix": "bot:flow completo",
"description": "Crear un flujo completo",
"body": [
"export const flow${1} = addKeyword(['categorias'])",
" .addAnswer('⚡ Tenemos las siguientes categorias')",
" .addAnswer(['🚀 Computadoras', '🚀 Celulares', '🚀 Otros'], {",
" delay: 1500, //Milisegundo 1500 = 1.5segundos",
"})"
]
}
}

3
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"recommendations": ["xyc.vscode-mdx-preview"]
}

15
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,15 @@
{
// Use IntelliSense para saber los atributos posibles.
// Mantenga el puntero para ver las descripciones de los existentes atributos.
// Para más información, visite: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Iniciar el programa",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}\\example-app\\app.js"
}
]
}

14
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,14 @@
{
"conventionalCommits.scopes": [
"hook",
"contributing",
"cli",
"bot",
"provider",
"adapter",
"ci",
"starters",
"conflict",
"contexts"
]
}

View File

@@ -0,0 +1,8 @@
/* eslint-disable */
module.exports = {
name: "@yarnpkg/plugin-postinstall",
factory: function (require) {
var plugin;(()=>{"use strict";var e={d:(t,n)=>{for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{default:()=>s});const n=require("@yarnpkg/core"),o=require("clipanion"),a={postinstall:{description:"Postinstall hook that will always run in Yarn v2",type:n.SettingsType.STRING,default:""}},r=require("@yarnpkg/shell"),l=async e=>{if(e){console.log("Running postinstall command...");const t=await r.execute(e);if(0!==t)throw new Error("postinstall command failed with exit code "+t)}};var i=function(e,t,n,o){var a,r=arguments.length,l=r<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,n):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)l=Reflect.decorate(e,t,n,o);else for(var i=e.length-1;i>=0;i--)(a=e[i])&&(l=(r<3?a(l):r>3?a(t,n,l):a(t,n))||l);return r>3&&l&&Object.defineProperty(t,n,l),l};class c extends o.Command{async execute(){const e=(await n.Configuration.find(this.context.cwd,this.context.plugins)).get("postinstall");await l(e)}}i([o.Command.Path("postinstall")],c.prototype,"execute",null);const s={configuration:a,commands:[c],hooks:{afterAllInstalled:async e=>{const t=e.configuration.get("postinstall");await l(t)}}};plugin=t})();
return plugin;
}
};

807
.yarn/releases/yarn-3.3.0.cjs vendored Normal file

File diff suppressed because one or more lines are too long

10
.yarnrc.yml Normal file
View File

@@ -0,0 +1,10 @@
nodeLinker: node-modules
npmPublishRegistry: 'https://registry.npmjs.org'
plugins:
- path: .yarn/plugins/@yarnpkg/plugin-postinstall.cjs
spec: 'https://raw.githubusercontent.com/gravitywelluk/yarn-plugin-postinstall/master/bundles/%40yarnpkg/plugin-postinstall.js'
yarnPath: .yarn/releases/yarn-3.3.0.cjs
postinstall: npx husky install

View File

@@ -1,14 +1,392 @@
#### Actualización 14 Ene 2022
- npm update
- remove ora and chalk
- add env
- add mysql
- add dialogflow
- add scan qr from webpage
- update route with middleware
- fix send message to story
- external download
- easy deploy heroku
- add support for ubuntu/linux
# Changelog
https://stackoverflow.com/questions/51855169/dialogflow-403-iam-permission-dialogflow-sessions-detectintent
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [0.1.3](https://github.com/leifermendez/bot-whatsapp/compare/v0.1.2...v0.1.3) (2023-01-04)
### Features
* **adapter:** :zap: send messages with dialogflow ([c20e151](https://github.com/leifermendez/bot-whatsapp/commit/c20e151e209d33de9e7425a64f003c85360f1832))
* **baileys:** added more methods ([1b23b83](https://github.com/leifermendez/bot-whatsapp/commit/1b23b837460ce4533ff33f10f1de5e3a344a5623))
* **bot:** :zap: http responses support ([e331c2d](https://github.com/leifermendez/bot-whatsapp/commit/e331c2dcc40eeb82a93f9d29f6a82333b8465927))
* **bot:** :zap: http responses support ([2d2bb08](https://github.com/leifermendez/bot-whatsapp/commit/2d2bb085cd95604a84ca3fe5c4ddc84b3824ac1c))
* **bot:** :zap: rev-03 everything work fine ([3012e02](https://github.com/leifermendez/bot-whatsapp/commit/3012e026b77ab4e99334b992d166a89189f76503))
* **cli:** :sparkles: added bailey ([06acec2](https://github.com/leifermendez/bot-whatsapp/commit/06acec2bf29d72c2b46f4ce81fed115bab97351f))
* **cli:** :sparkles: added bailey ([c868f73](https://github.com/leifermendez/bot-whatsapp/commit/c868f7346245bec94582b25a342febc657926c9d))
* **conflict:** :zap: remove unused variable ([eba9229](https://github.com/leifermendez/bot-whatsapp/commit/eba92299cfd84c971f09697d027043f19eec2b7c))
* **contexts:** :zap: add new dialogflowcx ([4d8cf62](https://github.com/leifermendez/bot-whatsapp/commit/4d8cf623ff86b3d08c8d52293d4e289dfda68e1c))
* **contexts:** :zap: add new dialogflowcx ([9885872](https://github.com/leifermendez/bot-whatsapp/commit/98858729919b2544dace07c49badce7888ddfd82))
* **contexts:** dialogflowcx support ([9179421](https://github.com/leifermendez/bot-whatsapp/commit/917942139f9736f1c0f8ce5f07b4e12e5768b0c7))
* correccion de flujos en app.js de ejemplo ([99f508f](https://github.com/leifermendez/bot-whatsapp/commit/99f508f93889d70240861158bc304c25a3b2daef))
* **docs:** master class updated ([69fd81a](https://github.com/leifermendez/bot-whatsapp/commit/69fd81a565e61b249ac50917585293d2d84e3dd4))
* **docs:** master class updated ([d522b03](https://github.com/leifermendez/bot-whatsapp/commit/d522b03e2e6e6e3f7c467c59e3d2d6f288fe37b2))
* **provider:** :bug: dialogflow ([4ec6f1e](https://github.com/leifermendez/bot-whatsapp/commit/4ec6f1e120879e545fa111615f2d79b792d947a5))
* **provider:** :sparkles: added dialogflow ([2f633c7](https://github.com/leifermendez/bot-whatsapp/commit/2f633c72da24f98d6c318d1e725571b62e04604c))
* **provider:** :sparkles: added dialogflow ([798f1ce](https://github.com/leifermendez/bot-whatsapp/commit/798f1cebdefe43624c1698a219dcb224bb842d38))
* **provider:** :sparkles: endpoint is added to validate the webhook … ([478929d](https://github.com/leifermendez/bot-whatsapp/commit/478929d1340d46d6bf997ae8edabbaae4511172d))
* **provider:** :sparkles: endpoint is added to validate the webhook token ([1ec1564](https://github.com/leifermendez/bot-whatsapp/commit/1ec15647dc462363d5b765f42debddbe6ef6266b))
* **provider:** :zap: add new methods ([0b4e353](https://github.com/leifermendez/bot-whatsapp/commit/0b4e35308dace0ccdf618cb1d04987ed5200d58c))
* **provider:** :zap: add sendfile and sendButtons ([5433610](https://github.com/leifermendez/bot-whatsapp/commit/5433610a84d7a050a387e4daf2ded1daebfc03a4))
* **provider:** :zap: add sendfile and sendButtons ([342cbcc](https://github.com/leifermendez/bot-whatsapp/commit/342cbccff1d09f9aabe5423ad6d686d590a2448f))
* **provider:** :zap: added new venom provider ([01fe9eb](https://github.com/leifermendez/bot-whatsapp/commit/01fe9ebc9a943f2aa086ee415153d1cccdb14ec0))
* **provider:** :zap: added tamplate venom ([337c2e9](https://github.com/leifermendez/bot-whatsapp/commit/337c2e94bccd0ae173958fe2db08b494bdc93c28))
* **provider:** :zap: baileysProvider ([23b2e8e](https://github.com/leifermendez/bot-whatsapp/commit/23b2e8e439ecec24450bd5cf1a3820316e643434))
* **provider:** :zap: solution error buttons ([1b83871](https://github.com/leifermendez/bot-whatsapp/commit/1b83871cca6996c6acae3d4c8b6b42aec05ea146))
* **provider:** :zap: solution error utils venom ([31c83f5](https://github.com/leifermendez/bot-whatsapp/commit/31c83f5d689a01490d3adb96006f54c2a5d3268b))
* **provider:** :zap: update ([b62d21a](https://github.com/leifermendez/bot-whatsapp/commit/b62d21a0bf94466e43c25c6e8c0f5db9ae91c572))
* **provider:** :zap: update ([0c94647](https://github.com/leifermendez/bot-whatsapp/commit/0c94647a27747c3ddf4f02926580370f0d81bdc2))
* **provider:** meta provider is added ([b041f7d](https://github.com/leifermendez/bot-whatsapp/commit/b041f7d0c7cc6f152d3f36785d1d398a4141d57d))
* **provider:** meta provider is added ([438607c](https://github.com/leifermendez/bot-whatsapp/commit/438607c222b91d6f8814201dabe5f7c3e7ba1abb))
* **provider:** new added baileys ([4e0fcbd](https://github.com/leifermendez/bot-whatsapp/commit/4e0fcbd8347f8a430adb43351b5415098a5d10df))
* **provider:** new provider - venon:zap: configuracion inicial provi… ([66f75f8](https://github.com/leifermendez/bot-whatsapp/commit/66f75f872200334bfc9eda744bed92c509dfee56))
* **provider:** new provider - venon:zap: configuracion inicial provider venom ([fee7c2e](https://github.com/leifermendez/bot-whatsapp/commit/fee7c2e967b7fe8835b5acc243c19f7713acfbe7))
* se agregaron los datros del adapter mongo en app.js y package.json ([8160d13](https://github.com/leifermendez/bot-whatsapp/commit/8160d13c866b8ae17b0ec8e68eee1bc0373595b0))
* se agrego informacion al ejemplo en app.js ([954e751](https://github.com/leifermendez/bot-whatsapp/commit/954e751f700c6a39ec70c0bc5168637c0dc7e07c))
* se agrego informacion al ejemplo en app.js ([b2f1339](https://github.com/leifermendez/bot-whatsapp/commit/b2f13396104db9ccef5b3bad1c4e19c6a4bad2d4))
* **starters:** meta memory base template added ([11c784f](https://github.com/leifermendez/bot-whatsapp/commit/11c784f882965d6bd3a2313cf91bed9fb3aa5f26))
* **starters:** meta memory base template added ([e8d6252](https://github.com/leifermendez/bot-whatsapp/commit/e8d625201ed86e162e0b4e82100ede1d08985555))
### Bug Fixes
* :art: update ([7d6708c](https://github.com/leifermendez/bot-whatsapp/commit/7d6708c01bbdc5043a7e6ed56fe15a9618115b91))
* :sparkles: updated starters ([5da4b7a](https://github.com/leifermendez/bot-whatsapp/commit/5da4b7a4d1e5950be94361ac439938741b9d299c))
* actualizar app.js de ejemplo ([1746613](https://github.com/leifermendez/bot-whatsapp/commit/17466138ddcef60a23a0c87911f22045f26d3233))
* actualizar ejemplo app.js ([60fdbf3](https://github.com/leifermendez/bot-whatsapp/commit/60fdbf3d3cd62819e618853a9dc2fd0e23fe8752))
* **adapter:** :fire: clear log ([9ad4874](https://github.com/leifermendez/bot-whatsapp/commit/9ad4874fdafabfbf0e9e20e6b3281f702bb9fbe7))
* **adapter:** :fire: clear log ([4d34d3a](https://github.com/leifermendez/bot-whatsapp/commit/4d34d3ab1daab4e72fb5244216c78cf836d1a164))
* **adapter:** :fire: improvement baileys ([e6fefb4](https://github.com/leifermendez/bot-whatsapp/commit/e6fefb4049847f996f2a169b9acfc27c2428d3e6))
* **adapter:** :fire: improvement baileys ([2d5ac26](https://github.com/leifermendez/bot-whatsapp/commit/2d5ac2664bea09e60ac85ff2612609ae21050945))
* **adapter:** :rocket: venom update - cli - qr iamge ([041bf62](https://github.com/leifermendez/bot-whatsapp/commit/041bf6280e5f6956393716907e0669aa3ca78b4a))
* **adapter:** :rocket: venom update - cli - qr iamge ([e37fd0d](https://github.com/leifermendez/bot-whatsapp/commit/e37fd0da3635aa1041664d490d5f9803d2c441ca))
* **adapter:** :rocket: venom update - cli - qr iamge ([ca6afbb](https://github.com/leifermendez/bot-whatsapp/commit/ca6afbb87fceec12d4a383486ad693905e36881f))
* **adapter:** json db change is made ([386c1bb](https://github.com/leifermendez/bot-whatsapp/commit/386c1bbbac036aa58335fb5f62e3af2493766b6b))
* **adapter:** json db change is made ([3bdc7af](https://github.com/leifermendez/bot-whatsapp/commit/3bdc7afe8062527ff08620650d2c1177dfea83f5))
* agregamos variables para mysql ([dcf65b8](https://github.com/leifermendez/bot-whatsapp/commit/dcf65b87bc7e7e6381e6448e83118077986898e7))
* **bot:** :ambulance: fix callback functions ([d9aa97c](https://github.com/leifermendez/bot-whatsapp/commit/d9aa97c7819aca1446657bc0b75e9732f0f20c6b)), closes [#252](https://github.com/leifermendez/bot-whatsapp/issues/252)
* **bot:** :ambulance: fix callback functions ([964a074](https://github.com/leifermendez/bot-whatsapp/commit/964a074aa41324bd09d0c4e2e7aa663a0602b69c))
* **bot:** :fire: fix rev ([21407c0](https://github.com/leifermendez/bot-whatsapp/commit/21407c0e37f1ab12efecf887e699cedf05e3946a))
* **bot:** :fire: fix rev ([484c8c3](https://github.com/leifermendez/bot-whatsapp/commit/484c8c3bdefbc7824c32a86090bafae0593ecdac))
* **bot:** :zap: working callback Phase 1 ([952ce86](https://github.com/leifermendez/bot-whatsapp/commit/952ce86ffaa48a0d6fbc0a00a08c5d1efa14ee8e))
* **bot:** :zap: working nested new flow ([2cbc962](https://github.com/leifermendez/bot-whatsapp/commit/2cbc96245d795de749d894a3a0d99b6550f08d9e))
* **cli:** :art: starters ([a2be57f](https://github.com/leifermendez/bot-whatsapp/commit/a2be57f0aa42c6b5e13ad19c34abc7d9e81dc135))
* **cli:** :art: starters ([670ecf1](https://github.com/leifermendez/bot-whatsapp/commit/670ecf121babf53e76c2ea106c0710cbe59facde))
* **cli:** :fire: update instructions ([e585e2f](https://github.com/leifermendez/bot-whatsapp/commit/e585e2f5f644ed0188dc9cd2b3c697c9d6050669))
* **cli:** :fire: update instructions ([ed36ce0](https://github.com/leifermendez/bot-whatsapp/commit/ed36ce0a7796320c6a4a452f29c05a3f0f7368db))
* **cli:** :fire: update instructions ([bad1694](https://github.com/leifermendez/bot-whatsapp/commit/bad16943fc2089887d6bf0b6d90075d3bec6f9c7))
* **cli:** :fire: update instructions ([a21633f](https://github.com/leifermendez/bot-whatsapp/commit/a21633fb7cf348cc37f4e4714f51172b49b193b5))
* **cli:** :zap: updated ([a6f4aa8](https://github.com/leifermendez/bot-whatsapp/commit/a6f4aa8d1e809330c06c165aaf9a9f90b8922bb5))
* **conflict:** conflict resolution ([71d43b5](https://github.com/leifermendez/bot-whatsapp/commit/71d43b585a0ce173061c84e9879915e4602db026))
* **contexts:** :fire: added buttons ([eabef7a](https://github.com/leifermendez/bot-whatsapp/commit/eabef7a92d005cd0190196cfe75828c38885aadf))
* **contexts:** :fire: added buttons ([1b878d2](https://github.com/leifermendez/bot-whatsapp/commit/1b878d2ba0daeb3609af74a2ebae7948456e7fb0))
* **contexts:** :fire: added buttons ([78b0a9d](https://github.com/leifermendez/bot-whatsapp/commit/78b0a9dddc2a6e0fceb721ee7794efa2047f25fc))
* **contexts:** :fire: added buttons ([d8309f7](https://github.com/leifermendez/bot-whatsapp/commit/d8309f77e1d9137c0bec977ed9faef633cd90552))
* correccion en app.js para remover addChild en starters ([32db429](https://github.com/leifermendez/bot-whatsapp/commit/32db429f2946f344d949cb169a9595d657c06279))
* fix del db provider mysql ([b59d4fc](https://github.com/leifermendez/bot-whatsapp/commit/b59d4fcdd7462cde3f68ab5746d49960b547a592))
* provider equivocado en app.js de venom ([4e0a109](https://github.com/leifermendez/bot-whatsapp/commit/4e0a1091ee85cedfaa5a9c3d40e5cd50bc36cda3))
* **provider:** :bug: create static site html qr ([c7e56a4](https://github.com/leifermendez/bot-whatsapp/commit/c7e56a4b13c8829f91769eeca7f1f6b3473f68cf))
* **provider:** :bug: fix metea provider ([85f50be](https://github.com/leifermendez/bot-whatsapp/commit/85f50be9dcbf3817107898d8d2980baf05acd678))
* **provider:** :bug: fix metea provider ([a52aaa1](https://github.com/leifermendez/bot-whatsapp/commit/a52aaa11d883bbaf526cf87720d3c3fd9f89a986))
* **provider:** :bug: qr code accurate ([6c4845d](https://github.com/leifermendez/bot-whatsapp/commit/6c4845d733720d9916bb4008f9069ae4fd986a4b))
* **provider:** :bug: qr code accurate ([91bfdc4](https://github.com/leifermendez/bot-whatsapp/commit/91bfdc46301207cbc5274308da6f39c7b4652c63))
* **provider:** :fire: baileys fix ([928365d](https://github.com/leifermendez/bot-whatsapp/commit/928365dcafb3631acf6b1d0c239a906f8e1c4b0d))
* **provider:** :fire: send message togther with media ([78aa23f](https://github.com/leifermendez/bot-whatsapp/commit/78aa23fab094059145f82e6781f9366d5d582b4f))
* **provider:** :fire: send message togther with media ([b6bf43d](https://github.com/leifermendez/bot-whatsapp/commit/b6bf43d70fc28c6a229522b9b0de76cec43ac864))
* **provider:** :zap: baileys fix restart ([ae83774](https://github.com/leifermendez/bot-whatsapp/commit/ae83774365027e2e86127ab7713ae9ee2df31f33))
* **provider:** :zap: edit starter ([ff65832](https://github.com/leifermendez/bot-whatsapp/commit/ff65832012003423cc86d25cf0923452b1f8acb7))
* **provider:** :zap: edit starter ([68dd182](https://github.com/leifermendez/bot-whatsapp/commit/68dd1820f05d04780824b318072d053eaf7db654))
* **provider:** :zap: json space ([3cef741](https://github.com/leifermendez/bot-whatsapp/commit/3cef741c9ee30024eb42770a5f32931fcd372160))
* **provider:** :zap: json space ([9b087e0](https://github.com/leifermendez/bot-whatsapp/commit/9b087e071019a7b6c79195a24dc7ddec498c5716))
* **provider:** :zap: json space ([208fb4e](https://github.com/leifermendez/bot-whatsapp/commit/208fb4e9131dd5d4fd7230ba1aa11181337d9181))
* **provider:** :zap: json space ([54a59c7](https://github.com/leifermendez/bot-whatsapp/commit/54a59c7f0d4dbaab006ce7e3c74412d8d3613ecd))
* **provider:** qr-fix margin ([663641a](https://github.com/leifermendez/bot-whatsapp/commit/663641a1b8bf9234a88b0f3c38381ebc4bfa4bf9))
* se quito addChild de las constantes porque no se usa ([ba2291a](https://github.com/leifermendez/bot-whatsapp/commit/ba2291a3ddac0d4101021e11d03cb222c5a4bb3b))
* **starters:** :fire: updated staters ([4d4f15c](https://github.com/leifermendez/bot-whatsapp/commit/4d4f15ce73486d9335ad474d9e37c3b155670134))
* **starters:** :fire: updated staters ([a30eaac](https://github.com/leifermendez/bot-whatsapp/commit/a30eaac77534d17eb980f6ec126140e9d30aa06e))
* **starters:** :memo: update MIGRATION ([37fe323](https://github.com/leifermendez/bot-whatsapp/commit/37fe32322eb1bd41eecd151e52f17ec0588fb85e))
* **starters:** :memo: update MIGRATION ([9b30e7d](https://github.com/leifermendez/bot-whatsapp/commit/9b30e7dcfc30bc160b56427cc6cdc2dc982bde2a))
* **starters:** base templates are added for meta ([229e017](https://github.com/leifermendez/bot-whatsapp/commit/229e017ae20b84c9d12c7282f97b7034f5f33e6d))
* **starters:** base templates are added for meta ([20f6651](https://github.com/leifermendez/bot-whatsapp/commit/20f665175c9b47226df41ce43e05574bd6ab1930))
### [0.1.2](https://github.com/leifermendez/bot-whatsapp/compare/v0.1.1...v0.1.2) (2022-12-12)
### Bug Fixes
* **cli:** :art: starters ([79e2318](https://github.com/leifermendez/bot-whatsapp/commit/79e231825613f33bfec2ae8e93139f885c199c7a))
* **cli:** :art: starters ([87ba43a](https://github.com/leifermendez/bot-whatsapp/commit/87ba43a5535be0893a7701a3b6a085ee5d29e7c5))
* fix dependencias ([61d0324](https://github.com/leifermendez/bot-whatsapp/commit/61d032426119341187a470035d49b8b252ca46cd))
### [0.1.1](https://github.com/leifermendez/bot-whatsapp/compare/v0.3.0...v0.1.1) (2022-12-12)
## 0.3.0 (2022-12-12)
### ⚠ BREAKING CHANGES
* 🧨 NO
### Features
* (🎸) add onClick prop to component ([4ae3898](https://github.com/leifermendez/bot-whatsapp/commit/4ae389846d38c133f6bb2129ae373eed39d9d08d))
* **adapter:** added adapter mysql ([717a7dc](https://github.com/leifermendez/bot-whatsapp/commit/717a7dc95fbc107ec6f55387aff606c47144baa4))
* **adapter:** implementation of json file adapter ([5e1a373](https://github.com/leifermendez/bot-whatsapp/commit/5e1a3737303c843095984f6357564ea18458362f))
* **adapter:** mysql adapter ([8d73c86](https://github.com/leifermendez/bot-whatsapp/commit/8d73c86946d07aa80e5b375b62b84a88b2892e03))
* **adapter:** sql is added to create the table ([4b7de0f](https://github.com/leifermendez/bot-whatsapp/commit/4b7de0f6901524fa2c09271c3a99c364e6b3c260))
* **bot:** :fire: improvement provider handler ([4154cc2](https://github.com/leifermendez/bot-whatsapp/commit/4154cc223091a46d3203d3a378cd42f61749a5fa))
* **bot:** :zap: add send image function ([ce8a96b](https://github.com/leifermendez/bot-whatsapp/commit/ce8a96b958ff814c65d8fb4dbd5eaed5cc83a1ed))
* **ci:** :art: add releases ([b115dc3](https://github.com/leifermendez/bot-whatsapp/commit/b115dc3654996f049837bfb6b5d039a2313df0ad))
* **ci:** :art: relases script ([2e906bc](https://github.com/leifermendez/bot-whatsapp/commit/2e906bce79f7d854d437334e1d0c2cd270b0bbc6))
* **ci:** update ci ([e5a9db7](https://github.com/leifermendez/bot-whatsapp/commit/e5a9db7e12340c4f5baa66e8b20585b63daa3bcf))
* **cli:** create-starter ([3977987](https://github.com/leifermendez/bot-whatsapp/commit/397798790ef5857ca758b0df8384c6a4bfacc181))
* **provider:** :fire: add twilii (weoking) ([4350dff](https://github.com/leifermendez/bot-whatsapp/commit/4350dff22a7de69ba6d35ecbdd67e59b810bd46f))
* **provider:** added twilio provider ([8dd3be9](https://github.com/leifermendez/bot-whatsapp/commit/8dd3be909b36717f6b54e141a5f48d2722d4855c))
* **release:** added ([1988948](https://github.com/leifermendez/bot-whatsapp/commit/1988948c30d922beb7b83faab96d1d59cf7f5f90))
* **release:** added ([f4ad704](https://github.com/leifermendez/bot-whatsapp/commit/f4ad7040abf619635480c30babd6f1159c7af85a))
### Bug Fixes
* **adapter:** conflict resolution ([4b307ef](https://github.com/leifermendez/bot-whatsapp/commit/4b307efe79c738a5c4e04ff1c07ca247d827593c))
* **adapter:** corrections are made to the adapter ([afa6771](https://github.com/leifermendez/bot-whatsapp/commit/afa677190392d48715930ebe2b1e15c7619d730f))
* **bot:** :zap: added delay promises ([73caf09](https://github.com/leifermendez/bot-whatsapp/commit/73caf090ba9013132e5dcb7761a10939dc9ac300))
* **bot:** :zap: fix sensitive case ([24ac9fb](https://github.com/leifermendez/bot-whatsapp/commit/24ac9fbf48f80eeb521a36bc938af3a70dd82303))
* **bot:** :zap: flow improvement + add utils ([a7b19d9](https://github.com/leifermendez/bot-whatsapp/commit/a7b19d9bff5ea66ff888555c3df37ae0e20b612a))
* **bot:** update ([49698bf](https://github.com/leifermendez/bot-whatsapp/commit/49698bfda9d2a53f7b1a7e1724a796698601fbaa))
* **ci:** :zap: balance version ([ec46cfd](https://github.com/leifermendez/bot-whatsapp/commit/ec46cfdd657c08c8e90261613f00cfc080f1e1d6))
* **ci:** :zap: github action ([b827a0a](https://github.com/leifermendez/bot-whatsapp/commit/b827a0ab225b89bb8117c82628db0679c09b4102))
* **ci:** :zap: github action ([4142ca4](https://github.com/leifermendez/bot-whatsapp/commit/4142ca4fd552e7005f3b1397a76b90a2e574d19d))
* **ci:** :zap: github action ([091544a](https://github.com/leifermendez/bot-whatsapp/commit/091544ac3fac0c16925e856e1aec64bcad0ecf6d))
* **ci:** :zap: github action ([2ce342a](https://github.com/leifermendez/bot-whatsapp/commit/2ce342a0cb15019d5084ca06dc30e342b030ea10))
* **ci:** :zap: github action ([7817793](https://github.com/leifermendez/bot-whatsapp/commit/781779328f93ef8b0e6e0f85c6cd05ae782112fb))
* **ci:** :zap: github action ([dfced8c](https://github.com/leifermendez/bot-whatsapp/commit/dfced8c594e9175c81e837af359631ba055b7e1a))
* **ci:** :zap: github action ([aaa4ce8](https://github.com/leifermendez/bot-whatsapp/commit/aaa4ce837229fd51e274de3d91e1d9d615ac69fd))
* **ci:** :zap: github action ([9ddf144](https://github.com/leifermendez/bot-whatsapp/commit/9ddf144244cd6877e7d26f576387814459f2befb))
* **ci:** :zap: github action ([b465de5](https://github.com/leifermendez/bot-whatsapp/commit/b465de55a0e511213d1a7760a74efa102172c85e))
* **ci:** :zap: github action ([cf1dc6f](https://github.com/leifermendez/bot-whatsapp/commit/cf1dc6fac810545e5a2b63f31f71322f37329e38))
* **ci:** :zap: github action ([8d897f8](https://github.com/leifermendez/bot-whatsapp/commit/8d897f824e27a55ca011163092a813a7e8f426af))
* **ci:** ci ([f55cfae](https://github.com/leifermendez/bot-whatsapp/commit/f55cfae6e4ccc1df949212999406680020d27f9c))
* **ci:** ci ([671c5b3](https://github.com/leifermendez/bot-whatsapp/commit/671c5b37f33360e8cb754625b8dd6e83bce9014d))
* **cli:** :bug: path ([32212fb](https://github.com/leifermendez/bot-whatsapp/commit/32212fb52d206bf6f8d753a86d9ce40aa0db2a5d))
* **cli:** :fire: create script - templates ([2319db3](https://github.com/leifermendez/bot-whatsapp/commit/2319db3009501fe57ae21e60ad286eb68c46f4fd))
* **cli:** :fire: create script - templates ([9cb98b5](https://github.com/leifermendez/bot-whatsapp/commit/9cb98b5e73fca3c3f5e70a8497badc31e494b943))
* **cli:** :fire: create script - templates ([2999e0e](https://github.com/leifermendez/bot-whatsapp/commit/2999e0e753f31a8b9e6d7c117e78cdb5656e203a))
* **cli:** :fire: create script - templates ([af716b7](https://github.com/leifermendez/bot-whatsapp/commit/af716b75372899877a81b528b58278376166d0ad))
* **cli:** :fire: create script - templates ([c6999c8](https://github.com/leifermendez/bot-whatsapp/commit/c6999c84931083a87b5717db58003be68244707e))
* **cli:** :fire: create script - templates ([d4b49a9](https://github.com/leifermendez/bot-whatsapp/commit/d4b49a9bd7085070f0c5964d2903f10b71bde0b3))
* **cli:** :fire: create script - templates ([eebc3c9](https://github.com/leifermendez/bot-whatsapp/commit/eebc3c980638d88f11a0d93b8344f3ff345c7ee5))
* **cli:** :zap: clean eslinter ([bfb69d9](https://github.com/leifermendez/bot-whatsapp/commit/bfb69d9a9574a757ae02748b6c5f5afa3eac68e6))
* **cli:** :zap: clean eslinter ([15f6972](https://github.com/leifermendez/bot-whatsapp/commit/15f697225775a0f0e0a440cd980f7fb8f51a1056))
* **cli:** :zap: create-starter ([d3b8310](https://github.com/leifermendez/bot-whatsapp/commit/d3b8310180d2ad813733b1d18f2c32d7d947740a))
* **cli:** :zap: update cli copy ([7797c2b](https://github.com/leifermendez/bot-whatsapp/commit/7797c2b46133697e2a591adab2b67e66b34a1cfe))
* **fix:** fix ([6483545](https://github.com/leifermendez/bot-whatsapp/commit/648354500b123f20044f5ac2e8a26b15f16d1b8d))
* **fix:** fix ([28c0480](https://github.com/leifermendez/bot-whatsapp/commit/28c0480b8bfa6b24394095f57c36ef89c9aeb566))
* **linter:** update linter and commitlint ([70a94ab](https://github.com/leifermendez/bot-whatsapp/commit/70a94ab2c6f8e4122780c77bc3a621944883e621))
* pre-copy fix ([08e2552](https://github.com/leifermendez/bot-whatsapp/commit/08e2552907c48cfeaac843457a18bf2032e6f8aa))
* pre-copy fix ([6617107](https://github.com/leifermendez/bot-whatsapp/commit/6617107ab824215c449e26eae6c2bb327ecfc092))
* **starter:** pre-copy fix ([929e74c](https://github.com/leifermendez/bot-whatsapp/commit/929e74c84b667ec13cb5490b3b951cb8df15ebd1))
* (💍) Is justa test! ([37d04e9](https://github.com/leifermendez/bot-whatsapp/commit/37d04e9e89d3f01fdc367654ba60fb11ab2614c4))
### [0.2.1](https://github.com/leifermendez/bot-whatsapp/compare/v0.2.0...v0.2.1) (2022-12-12)
## 0.2.0 (2022-12-12)
### ⚠ BREAKING CHANGES
* 🧨 NO
### Features
* (🎸) add onClick prop to component ([4ae3898](https://github.com/leifermendez/bot-whatsapp/commit/4ae389846d38c133f6bb2129ae373eed39d9d08d))
* **adapter:** added adapter mysql ([717a7dc](https://github.com/leifermendez/bot-whatsapp/commit/717a7dc95fbc107ec6f55387aff606c47144baa4))
* **adapter:** implementation of json file adapter ([5e1a373](https://github.com/leifermendez/bot-whatsapp/commit/5e1a3737303c843095984f6357564ea18458362f))
* **adapter:** mysql adapter ([8d73c86](https://github.com/leifermendez/bot-whatsapp/commit/8d73c86946d07aa80e5b375b62b84a88b2892e03))
* **adapter:** sql is added to create the table ([4b7de0f](https://github.com/leifermendez/bot-whatsapp/commit/4b7de0f6901524fa2c09271c3a99c364e6b3c260))
* **bot:** :fire: improvement provider handler ([4154cc2](https://github.com/leifermendez/bot-whatsapp/commit/4154cc223091a46d3203d3a378cd42f61749a5fa))
* **bot:** :zap: add send image function ([ce8a96b](https://github.com/leifermendez/bot-whatsapp/commit/ce8a96b958ff814c65d8fb4dbd5eaed5cc83a1ed))
* **ci:** :art: add releases ([b115dc3](https://github.com/leifermendez/bot-whatsapp/commit/b115dc3654996f049837bfb6b5d039a2313df0ad))
* **ci:** :art: relases script ([2e906bc](https://github.com/leifermendez/bot-whatsapp/commit/2e906bce79f7d854d437334e1d0c2cd270b0bbc6))
* **ci:** update ci ([e5a9db7](https://github.com/leifermendez/bot-whatsapp/commit/e5a9db7e12340c4f5baa66e8b20585b63daa3bcf))
* **cli:** create-starter ([3977987](https://github.com/leifermendez/bot-whatsapp/commit/397798790ef5857ca758b0df8384c6a4bfacc181))
* **provider:** :fire: add twilii (weoking) ([4350dff](https://github.com/leifermendez/bot-whatsapp/commit/4350dff22a7de69ba6d35ecbdd67e59b810bd46f))
* **provider:** added twilio provider ([8dd3be9](https://github.com/leifermendez/bot-whatsapp/commit/8dd3be909b36717f6b54e141a5f48d2722d4855c))
* **release:** added ([1988948](https://github.com/leifermendez/bot-whatsapp/commit/1988948c30d922beb7b83faab96d1d59cf7f5f90))
* **release:** added ([f4ad704](https://github.com/leifermendez/bot-whatsapp/commit/f4ad7040abf619635480c30babd6f1159c7af85a))
### Bug Fixes
* **adapter:** conflict resolution ([4b307ef](https://github.com/leifermendez/bot-whatsapp/commit/4b307efe79c738a5c4e04ff1c07ca247d827593c))
* **adapter:** corrections are made to the adapter ([afa6771](https://github.com/leifermendez/bot-whatsapp/commit/afa677190392d48715930ebe2b1e15c7619d730f))
* **bot:** :zap: added delay promises ([73caf09](https://github.com/leifermendez/bot-whatsapp/commit/73caf090ba9013132e5dcb7761a10939dc9ac300))
* **bot:** :zap: fix sensitive case ([24ac9fb](https://github.com/leifermendez/bot-whatsapp/commit/24ac9fbf48f80eeb521a36bc938af3a70dd82303))
* **bot:** :zap: flow improvement + add utils ([a7b19d9](https://github.com/leifermendez/bot-whatsapp/commit/a7b19d9bff5ea66ff888555c3df37ae0e20b612a))
* **bot:** update ([49698bf](https://github.com/leifermendez/bot-whatsapp/commit/49698bfda9d2a53f7b1a7e1724a796698601fbaa))
* **ci:** :zap: balance version ([ec46cfd](https://github.com/leifermendez/bot-whatsapp/commit/ec46cfdd657c08c8e90261613f00cfc080f1e1d6))
* **ci:** :zap: github action ([b827a0a](https://github.com/leifermendez/bot-whatsapp/commit/b827a0ab225b89bb8117c82628db0679c09b4102))
* **ci:** :zap: github action ([4142ca4](https://github.com/leifermendez/bot-whatsapp/commit/4142ca4fd552e7005f3b1397a76b90a2e574d19d))
* **ci:** :zap: github action ([091544a](https://github.com/leifermendez/bot-whatsapp/commit/091544ac3fac0c16925e856e1aec64bcad0ecf6d))
* **ci:** :zap: github action ([2ce342a](https://github.com/leifermendez/bot-whatsapp/commit/2ce342a0cb15019d5084ca06dc30e342b030ea10))
* **ci:** :zap: github action ([7817793](https://github.com/leifermendez/bot-whatsapp/commit/781779328f93ef8b0e6e0f85c6cd05ae782112fb))
* **ci:** :zap: github action ([dfced8c](https://github.com/leifermendez/bot-whatsapp/commit/dfced8c594e9175c81e837af359631ba055b7e1a))
* **ci:** :zap: github action ([aaa4ce8](https://github.com/leifermendez/bot-whatsapp/commit/aaa4ce837229fd51e274de3d91e1d9d615ac69fd))
* **ci:** :zap: github action ([9ddf144](https://github.com/leifermendez/bot-whatsapp/commit/9ddf144244cd6877e7d26f576387814459f2befb))
* **ci:** :zap: github action ([b465de5](https://github.com/leifermendez/bot-whatsapp/commit/b465de55a0e511213d1a7760a74efa102172c85e))
* **ci:** :zap: github action ([cf1dc6f](https://github.com/leifermendez/bot-whatsapp/commit/cf1dc6fac810545e5a2b63f31f71322f37329e38))
* **ci:** :zap: github action ([8d897f8](https://github.com/leifermendez/bot-whatsapp/commit/8d897f824e27a55ca011163092a813a7e8f426af))
* **ci:** ci ([f55cfae](https://github.com/leifermendez/bot-whatsapp/commit/f55cfae6e4ccc1df949212999406680020d27f9c))
* **ci:** ci ([671c5b3](https://github.com/leifermendez/bot-whatsapp/commit/671c5b37f33360e8cb754625b8dd6e83bce9014d))
* **cli:** :bug: path ([32212fb](https://github.com/leifermendez/bot-whatsapp/commit/32212fb52d206bf6f8d753a86d9ce40aa0db2a5d))
* **cli:** :fire: create script - templates ([2319db3](https://github.com/leifermendez/bot-whatsapp/commit/2319db3009501fe57ae21e60ad286eb68c46f4fd))
* **cli:** :fire: create script - templates ([9cb98b5](https://github.com/leifermendez/bot-whatsapp/commit/9cb98b5e73fca3c3f5e70a8497badc31e494b943))
* **cli:** :fire: create script - templates ([2999e0e](https://github.com/leifermendez/bot-whatsapp/commit/2999e0e753f31a8b9e6d7c117e78cdb5656e203a))
* **cli:** :fire: create script - templates ([af716b7](https://github.com/leifermendez/bot-whatsapp/commit/af716b75372899877a81b528b58278376166d0ad))
* **cli:** :fire: create script - templates ([c6999c8](https://github.com/leifermendez/bot-whatsapp/commit/c6999c84931083a87b5717db58003be68244707e))
* **cli:** :fire: create script - templates ([d4b49a9](https://github.com/leifermendez/bot-whatsapp/commit/d4b49a9bd7085070f0c5964d2903f10b71bde0b3))
* **cli:** :fire: create script - templates ([eebc3c9](https://github.com/leifermendez/bot-whatsapp/commit/eebc3c980638d88f11a0d93b8344f3ff345c7ee5))
* **cli:** :zap: clean eslinter ([bfb69d9](https://github.com/leifermendez/bot-whatsapp/commit/bfb69d9a9574a757ae02748b6c5f5afa3eac68e6))
* **cli:** :zap: clean eslinter ([15f6972](https://github.com/leifermendez/bot-whatsapp/commit/15f697225775a0f0e0a440cd980f7fb8f51a1056))
* **cli:** :zap: create-starter ([d3b8310](https://github.com/leifermendez/bot-whatsapp/commit/d3b8310180d2ad813733b1d18f2c32d7d947740a))
* **cli:** :zap: update cli copy ([7797c2b](https://github.com/leifermendez/bot-whatsapp/commit/7797c2b46133697e2a591adab2b67e66b34a1cfe))
* **fix:** fix ([6483545](https://github.com/leifermendez/bot-whatsapp/commit/648354500b123f20044f5ac2e8a26b15f16d1b8d))
* **fix:** fix ([28c0480](https://github.com/leifermendez/bot-whatsapp/commit/28c0480b8bfa6b24394095f57c36ef89c9aeb566))
* **linter:** update linter and commitlint ([70a94ab](https://github.com/leifermendez/bot-whatsapp/commit/70a94ab2c6f8e4122780c77bc3a621944883e621))
* pre-copy fix ([08e2552](https://github.com/leifermendez/bot-whatsapp/commit/08e2552907c48cfeaac843457a18bf2032e6f8aa))
* pre-copy fix ([6617107](https://github.com/leifermendez/bot-whatsapp/commit/6617107ab824215c449e26eae6c2bb327ecfc092))
* **starter:** pre-copy fix ([929e74c](https://github.com/leifermendez/bot-whatsapp/commit/929e74c84b667ec13cb5490b3b951cb8df15ebd1))
* (💍) Is justa test! ([37d04e9](https://github.com/leifermendez/bot-whatsapp/commit/37d04e9e89d3f01fdc367654ba60fb11ab2614c4))
### [0.0.3](https://github.com/leifermendez/bot-whatsapp/compare/v0.2.0...v0.0.3) (2022-12-12)
## 0.2.0 (2022-12-12)
### ⚠ BREAKING CHANGES
* 🧨 NO
### Features
* (🎸) add onClick prop to component ([4ae3898](https://github.com/leifermendez/bot-whatsapp/commit/4ae389846d38c133f6bb2129ae373eed39d9d08d))
* **adapter:** added adapter mysql ([717a7dc](https://github.com/leifermendez/bot-whatsapp/commit/717a7dc95fbc107ec6f55387aff606c47144baa4))
* **adapter:** implementation of json file adapter ([5e1a373](https://github.com/leifermendez/bot-whatsapp/commit/5e1a3737303c843095984f6357564ea18458362f))
* **adapter:** mysql adapter ([8d73c86](https://github.com/leifermendez/bot-whatsapp/commit/8d73c86946d07aa80e5b375b62b84a88b2892e03))
* **adapter:** sql is added to create the table ([4b7de0f](https://github.com/leifermendez/bot-whatsapp/commit/4b7de0f6901524fa2c09271c3a99c364e6b3c260))
* **bot:** :fire: improvement provider handler ([4154cc2](https://github.com/leifermendez/bot-whatsapp/commit/4154cc223091a46d3203d3a378cd42f61749a5fa))
* **bot:** :zap: add send image function ([ce8a96b](https://github.com/leifermendez/bot-whatsapp/commit/ce8a96b958ff814c65d8fb4dbd5eaed5cc83a1ed))
* **ci:** :art: add releases ([b115dc3](https://github.com/leifermendez/bot-whatsapp/commit/b115dc3654996f049837bfb6b5d039a2313df0ad))
* **ci:** :art: relases script ([2e906bc](https://github.com/leifermendez/bot-whatsapp/commit/2e906bce79f7d854d437334e1d0c2cd270b0bbc6))
* **ci:** update ci ([e5a9db7](https://github.com/leifermendez/bot-whatsapp/commit/e5a9db7e12340c4f5baa66e8b20585b63daa3bcf))
* **cli:** create-starter ([3977987](https://github.com/leifermendez/bot-whatsapp/commit/397798790ef5857ca758b0df8384c6a4bfacc181))
* **provider:** :fire: add twilii (weoking) ([4350dff](https://github.com/leifermendez/bot-whatsapp/commit/4350dff22a7de69ba6d35ecbdd67e59b810bd46f))
* **provider:** added twilio provider ([8dd3be9](https://github.com/leifermendez/bot-whatsapp/commit/8dd3be909b36717f6b54e141a5f48d2722d4855c))
* **release:** added ([1988948](https://github.com/leifermendez/bot-whatsapp/commit/1988948c30d922beb7b83faab96d1d59cf7f5f90))
* **release:** added ([f4ad704](https://github.com/leifermendez/bot-whatsapp/commit/f4ad7040abf619635480c30babd6f1159c7af85a))
### Bug Fixes
* **adapter:** conflict resolution ([4b307ef](https://github.com/leifermendez/bot-whatsapp/commit/4b307efe79c738a5c4e04ff1c07ca247d827593c))
* **adapter:** corrections are made to the adapter ([afa6771](https://github.com/leifermendez/bot-whatsapp/commit/afa677190392d48715930ebe2b1e15c7619d730f))
* **bot:** :zap: added delay promises ([73caf09](https://github.com/leifermendez/bot-whatsapp/commit/73caf090ba9013132e5dcb7761a10939dc9ac300))
* **bot:** :zap: fix sensitive case ([24ac9fb](https://github.com/leifermendez/bot-whatsapp/commit/24ac9fbf48f80eeb521a36bc938af3a70dd82303))
* **bot:** :zap: flow improvement + add utils ([a7b19d9](https://github.com/leifermendez/bot-whatsapp/commit/a7b19d9bff5ea66ff888555c3df37ae0e20b612a))
* **bot:** update ([49698bf](https://github.com/leifermendez/bot-whatsapp/commit/49698bfda9d2a53f7b1a7e1724a796698601fbaa))
* **ci:** :zap: balance version ([ec46cfd](https://github.com/leifermendez/bot-whatsapp/commit/ec46cfdd657c08c8e90261613f00cfc080f1e1d6))
* **ci:** :zap: github action ([b827a0a](https://github.com/leifermendez/bot-whatsapp/commit/b827a0ab225b89bb8117c82628db0679c09b4102))
* **ci:** :zap: github action ([4142ca4](https://github.com/leifermendez/bot-whatsapp/commit/4142ca4fd552e7005f3b1397a76b90a2e574d19d))
* **ci:** :zap: github action ([091544a](https://github.com/leifermendez/bot-whatsapp/commit/091544ac3fac0c16925e856e1aec64bcad0ecf6d))
* **ci:** :zap: github action ([2ce342a](https://github.com/leifermendez/bot-whatsapp/commit/2ce342a0cb15019d5084ca06dc30e342b030ea10))
* **ci:** :zap: github action ([7817793](https://github.com/leifermendez/bot-whatsapp/commit/781779328f93ef8b0e6e0f85c6cd05ae782112fb))
* **ci:** :zap: github action ([dfced8c](https://github.com/leifermendez/bot-whatsapp/commit/dfced8c594e9175c81e837af359631ba055b7e1a))
* **ci:** :zap: github action ([aaa4ce8](https://github.com/leifermendez/bot-whatsapp/commit/aaa4ce837229fd51e274de3d91e1d9d615ac69fd))
* **ci:** :zap: github action ([9ddf144](https://github.com/leifermendez/bot-whatsapp/commit/9ddf144244cd6877e7d26f576387814459f2befb))
* **ci:** :zap: github action ([b465de5](https://github.com/leifermendez/bot-whatsapp/commit/b465de55a0e511213d1a7760a74efa102172c85e))
* **ci:** :zap: github action ([cf1dc6f](https://github.com/leifermendez/bot-whatsapp/commit/cf1dc6fac810545e5a2b63f31f71322f37329e38))
* **ci:** :zap: github action ([8d897f8](https://github.com/leifermendez/bot-whatsapp/commit/8d897f824e27a55ca011163092a813a7e8f426af))
* **ci:** ci ([f55cfae](https://github.com/leifermendez/bot-whatsapp/commit/f55cfae6e4ccc1df949212999406680020d27f9c))
* **ci:** ci ([671c5b3](https://github.com/leifermendez/bot-whatsapp/commit/671c5b37f33360e8cb754625b8dd6e83bce9014d))
* **cli:** :bug: path ([32212fb](https://github.com/leifermendez/bot-whatsapp/commit/32212fb52d206bf6f8d753a86d9ce40aa0db2a5d))
* **cli:** :fire: create script - templates ([2319db3](https://github.com/leifermendez/bot-whatsapp/commit/2319db3009501fe57ae21e60ad286eb68c46f4fd))
* **cli:** :fire: create script - templates ([9cb98b5](https://github.com/leifermendez/bot-whatsapp/commit/9cb98b5e73fca3c3f5e70a8497badc31e494b943))
* **cli:** :fire: create script - templates ([2999e0e](https://github.com/leifermendez/bot-whatsapp/commit/2999e0e753f31a8b9e6d7c117e78cdb5656e203a))
* **cli:** :fire: create script - templates ([af716b7](https://github.com/leifermendez/bot-whatsapp/commit/af716b75372899877a81b528b58278376166d0ad))
* **cli:** :fire: create script - templates ([c6999c8](https://github.com/leifermendez/bot-whatsapp/commit/c6999c84931083a87b5717db58003be68244707e))
* **cli:** :fire: create script - templates ([d4b49a9](https://github.com/leifermendez/bot-whatsapp/commit/d4b49a9bd7085070f0c5964d2903f10b71bde0b3))
* **cli:** :fire: create script - templates ([eebc3c9](https://github.com/leifermendez/bot-whatsapp/commit/eebc3c980638d88f11a0d93b8344f3ff345c7ee5))
* **cli:** :zap: clean eslinter ([bfb69d9](https://github.com/leifermendez/bot-whatsapp/commit/bfb69d9a9574a757ae02748b6c5f5afa3eac68e6))
* **cli:** :zap: clean eslinter ([15f6972](https://github.com/leifermendez/bot-whatsapp/commit/15f697225775a0f0e0a440cd980f7fb8f51a1056))
* **cli:** :zap: create-starter ([d3b8310](https://github.com/leifermendez/bot-whatsapp/commit/d3b8310180d2ad813733b1d18f2c32d7d947740a))
* **cli:** :zap: update cli copy ([7797c2b](https://github.com/leifermendez/bot-whatsapp/commit/7797c2b46133697e2a591adab2b67e66b34a1cfe))
* **fix:** fix ([6483545](https://github.com/leifermendez/bot-whatsapp/commit/648354500b123f20044f5ac2e8a26b15f16d1b8d))
* **fix:** fix ([28c0480](https://github.com/leifermendez/bot-whatsapp/commit/28c0480b8bfa6b24394095f57c36ef89c9aeb566))
* **linter:** update linter and commitlint ([70a94ab](https://github.com/leifermendez/bot-whatsapp/commit/70a94ab2c6f8e4122780c77bc3a621944883e621))
* pre-copy fix ([08e2552](https://github.com/leifermendez/bot-whatsapp/commit/08e2552907c48cfeaac843457a18bf2032e6f8aa))
* pre-copy fix ([6617107](https://github.com/leifermendez/bot-whatsapp/commit/6617107ab824215c449e26eae6c2bb327ecfc092))
* **starter:** pre-copy fix ([929e74c](https://github.com/leifermendez/bot-whatsapp/commit/929e74c84b667ec13cb5490b3b951cb8df15ebd1))
* (💍) Is justa test! ([37d04e9](https://github.com/leifermendez/bot-whatsapp/commit/37d04e9e89d3f01fdc367654ba60fb11ab2614c4))
## 0.2.0-alpha.0 (2022-12-01)
### ⚠ BREAKING CHANGES
* 🧨 NO
### Features
* (🎸) add onClick prop to component ([4ae3898](https://github.com/leifermendez/bot-whatsapp/commit/4ae389846d38c133f6bb2129ae373eed39d9d08d))
### Bug Fixes
* **ci:** ci ([f55cfae](https://github.com/leifermendez/bot-whatsapp/commit/f55cfae6e4ccc1df949212999406680020d27f9c))
* **ci:** ci ([671c5b3](https://github.com/leifermendez/bot-whatsapp/commit/671c5b37f33360e8cb754625b8dd6e83bce9014d))
* **linter:** update linter and commitlint ([70a94ab](https://github.com/leifermendez/bot-whatsapp/commit/70a94ab2c6f8e4122780c77bc3a621944883e621))
* (💍) Is justa test! ([37d04e9](https://github.com/leifermendez/bot-whatsapp/commit/37d04e9e89d3f01fdc367654ba60fb11ab2614c4))
## 0.1.0 (2022-11-29)
### ⚠ BREAKING CHANGES
* 🧨 NO
### Features
* (🎸) add onClick prop to component ([4ae3898](https://github.com/leifermendez/bot-whatsapp/commit/4ae389846d38c133f6bb2129ae373eed39d9d08d))
### Bug Fixes
* **ci:** ci ([f55cfae](https://github.com/leifermendez/bot-whatsapp/commit/f55cfae6e4ccc1df949212999406680020d27f9c))
* **ci:** ci ([671c5b3](https://github.com/leifermendez/bot-whatsapp/commit/671c5b37f33360e8cb754625b8dd6e83bce9014d))
* (💍) Is justa test! ([37d04e9](https://github.com/leifermendez/bot-whatsapp/commit/37d04e9e89d3f01fdc367654ba60fb11ab2614c4))
#### Actualización 14 Ene 2022
- npm update
- remove ora and chalk
- add env
- add mysql
- add dialogflow
- add scan qr from webpage
- update route with middleware
- fix send message to story
- external download
- easy deploy heroku
- add support for ubuntu/linux
https://stackoverflow.com/questions/51855169/dialogflow-403-iam-permission-dialogflow-sessions-detectintent

103
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,103 @@
# CONTRIBUTING
### 📄 Bienvenido/a
Si deseas colaborar con el proyecto existen varias maneras, la primera de ellas es aportando conocimiento y mejorando el repositorio (actualizando documentación, mejorando código, revisando __[issues](https://github.com/codigoencasa/bot-whatsapp/issues)__, etc).
También es bien recibido los aportes económicos que se utilizaran para diferentes fines __[ver más](https://opencollective.com/bot-whatsapp)__
El lenguaje principal que se utilizó para desarrollar este proyecto fue __JavaScript__ con el fin de qué personas que están iniciando en el mundo de la programación puedan entender fácilmente.
### 🤔 Preguntas frecuentes
- ¿Como puedo hacer aportaciones de código en el proyecto?: [Ver Video](https://youtu.be/Lxt8Acob6aU)
- ¿Como ejecutar el entorno de pruebas?: [Ver Video](https://youtu.be/Mf9V-dloBfk)
- ¿Como crear un nuevo proveedor?: [Ver Video](https://youtu.be/cahK9zH3SI8)
- ¿Que son los GithubActions?: [Ver Video](https://youtu.be/nYBEBFKLiqw)
- ¿Canales de comunicación?: [Discord](https://link.codigoencasa.com/DISCORD)
-----
![](https://i.giphy.com/media/ntMt6TvalpstTIx7Ak/giphy.webp)
__Requerimientos:__
- Node v16 o superior __[descargar node](https://nodejs.org/es/download/)__
- __[Yarn](https://classic.yarnpkg.com/lang/en/docs/install/#windows-stable)__ como gestor de paquetes. En el link conseguirás las intrucciones para instalar yarn.
- __[VSCode](https://code.visualstudio.com/download)__ (recomendado): Editor de código con plugins.
- __[Conventional Commits](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits&ssr=false#overview)__ (plugin-vscode) este plugin te ayudará a crear commit semántico.
- Se usará la rama __dev__ *(https://github.com/leifermendez/bot-whatsapp/tree/dev)* como rama principal hasta que se haga oficialmente el lanzamiento de la V2.
### 🚀 Iniciando
__Clonar repo rama dev__
```
git clone --branch dev https://github.com/codigoencasa/bot-whatsapp
```
__Instalar dependencias__
```
cd bot-whatsapp
yarn install
```
__Compilar (build)__
Para compilar la aplicación es necesario ejecutar este comando, el cual genera un directorio `lib` dentro de los paquetes del monorepo.
```
yarn build
```
__Example-app__
Se ejecuta el CLI (Command Line Interface) para ayudarte a crear un app-bot de ejemplo.
```
yarn run cli
```
Selecionas (mediante las flechas arriba y abajo) el proveedor que quieras usar y cuando estes sobre el presiona la barra de espacio, igualmente selecciona la base de datos que quieras usar.
Se creó un subdirecorio con el nombre del proveedor y base de datos que seleccionaste, ejemplo: `base-bailey-mysql`
Dentro de ese directorio necesitas editar el archivo package.json y borrar las siguientes lineas:
```
"@bot-whatsapp/bot": "latest",
"@bot-whatsapp/cli": "latest",
"@bot-whatsapp/database": "latest",
"@bot-whatsapp/provider": "latest",
```
Cambiate al directorio creado ejemplo: `base-bailey-mysql`
```
cd base-baileys-mysql
```
Ejecuta los comandos:
```
npm install
npm run pre-copy
npm start
```
En el caso de MySql y Mongo es necesario especificar en app.js los datos de la conexión, ejemplo de MySql:
```
const BaileysProvider = require('@bot-whatsapp/provider/baileys')
const MySQLAdapter = require('@bot-whatsapp/database/mysql')
/**
* Declaramos las conexiones de MySQL
*/
const MYSQL_DB_HOST = 'localhost'
const MYSQL_DB_USER = 'usr'
const MYSQL_DB_PASSWORD = 'pass'
const MYSQL_DB_NAME = 'bot'
```
<!-- __Seguir instrucciones__
En la consola encontraras los pasos a seguir -->
![](https://i.imgur.com/dC6lEwy.png)
> __NOTA:__ [Eres libre de aportar informacion a este documento o arreglar ortografia 🤣](
https://github.com/codigoencasa/bot-whatsapp/edit/dev/CONTRIBUTING.md)
------
- [Discord](https://link.codigoencasa.com/DISCORD)
- [Twitter](https://twitter.com/leifermendez)
- [Youtube](https://www.youtube.com/watch?v=5lEMCeWEJ8o&list=PL_WGMLcL4jzWPhdhcUyhbFU6bC0oJd2BR)
- [Telegram](https://t.me/leifermendez)

88
EXAMPLE.md Normal file
View File

@@ -0,0 +1,88 @@
```js
const {
createBot,
createProvider,
createFlow,
addKeyword,
toSerialize,
} = require('@bot-whatsapp/bot')
const WebWhatsappProvider = require('@bot-whatsapp/provider/web-whatsapp')
const MongoAdapter = require('@bot-whatsapp/database/mongo')
const flowArepa1 = toSerialize(
addKeyword(['1', 'AREPA14'])
.addAnswer('Esta es una arepa calificada ⭐⭐⭐⭐⭐')
.addAnswer(['Ingredientes:', '10g Aguacate', '20g Huevo'].join('\n'))
.toJson()
)
const flowArepa2_2 = toSerialize(
addKeyword('SI').addAnswer('te pongo huevo de mentira!').toJson()
)
const flowArepa2 = toSerialize(
addKeyword(['arepa2'])
.addAnswer('Esta es una arepa calificada ⭐⭐⭐⭐')
.addAnswer(
['Ingredientes:', '10g perico', '20g huevo', '10g queso'].join('\n')
)
.addAnswer(
'Eres Vegano SI o NO',
{
capture: true,
},
null,
[...flowArepa2_2]
)
.toJson()
)
const flowArepa3 = toSerialize(
addKeyword(['arepa3'])
.addAnswer('Esta es una arepa calificada LAMEJOR ⭐⭐⭐⭐⭐')
.toJson()
)
//////////////--MENU--PRINCIPAL--//////////////////
const flujoMenuArepa = addKeyword(['hola', 'ola', 'buenos'])
.addAnswer('Bienvenido "Arepera Aji Picante 🤯🚀😅"')
.addAnswer(
[
'El menú de hoy es el siguiente:',
'👉 [1 -AREPA14] - Arepa tradicional con Aguacate y Huevo',
'👉 [arepa2] - Arepa rellena de perico y huevo con un toque de queso',
'👉 [arepa3] - Rellena de Jamon y Queso',
].join('\n')
)
.addAnswer(
'Esperando respuesta...',
{
capture: true,
},
() => {
console.log('Enviar un mail!')
},
[...flowArepa1, ...flowArepa2, ...flowArepa3]
)
.addAnswer('Gracias!')
const main = async () => {
const adapterDB = new MongoAdapter()
const adapterFlow = createFlow([flujoMenuArepa])
const adapterProvider = createProvider(WebWhatsappProvider)
createBot({
flow: adapterFlow,
provider: adapterProvider,
database: adapterDB,
})
}
main()
```

2
GLOSSARY.md Normal file
View File

@@ -0,0 +1,2 @@
CTX: Es el objeto que representa un mensaje, con opciones, id, ref
messageInComming: Objeto entrante del provider {body, from,to,...}

214
MIGRATION.md Normal file
View File

@@ -0,0 +1,214 @@
# Migración
#### Versión (legacy)
En la ***versión (legacy)*** se implementaban los flujos de esta manera, en dos archivos independientes.
> __`initial.json`__ para establecer las palabras claves y el flujo a responder, por otro lado tambien se necesitaba implementar
> __`response.json`__ donde se escriben los mensajes a responder.
```json
//initial.json
[
{
"keywords": [
"hola",
"ola",
"alo"
],
"key": "hola"
},
{
"keywords": ["productos", "info"],
"key": "productos"
},
{
"keywords": ["adios", "bye"],
"key": "adios"
},
{
"keywords": ["imagen", "foto"],
"key": "catalogo"
}
]
```
```json
//response.json
{
"hola":{
"replyMessage":[
"Gracias a ti! \n"
],
"media":null,
"trigger":null
},
"adios":{
"replyMessage":[
"Que te vaya bien!!"
],
},
"productos":{
"replyMessage":[
"Más productos aquí"
],
"trigger":null,
"actions":{
"title":"¿Que te interesa ver?",
"message":"Abajo unos botons",
"footer":"",
"buttons":[
{"body":"Telefonos"},
{"body":"Computadoras"},
{"body":"Otros"}
]
}
},
"catalogo":{
"replyMessage":[
"Te envio una imagen"
],
"media":"https://media2.giphy.com/media/VQJu0IeULuAmCwf5SL/giphy.gif",
"trigger":null,
},
}
```
#### Versión 2 (0.2.X)
En esta versión es mucho más sencillo, abajo encontraras un ejemplo del mismo flujo anteriormente mostrado.
```js
//app.js
const {
createBot,
createProvider,
createFlow,
addKeyword,
addChild,
} = require('@bot-whatsapp/bot')
const BaileysProvider = require('@bot-whatsapp/provider/baileys')
const MockAdapter = require('@bot-whatsapp/database/mock')
/**
* Declarando flujos principales.
*/
const flowHola = addKeyword(['hola', 'ola', 'alo'])
.addAnswer('Bienvenido a tu tienda online!')
const flowAdios = addKeyword(['adios', 'bye'])
.addAnswer('Que te vaya bien!!')
.addAnswer('Hasta luego!')
const flowProductos = addKeyword(['productos', 'info'])
.addAnswer('Te envio una imagen', {
buttons:[
{body:"Telefonos"},
{body:"Computadoras"},
{body:"Otros"}
]
})
const flowCatalogo = addKeyword(['imagen', 'foto'])
.addAnswer('Te envio una imagen', {media:'https://media2.giphy.com/media/VQJu0IeULuAmCwf5SL/giphy.gif'})
const main = async () => {
const adapterDB = new MockAdapter()
const adapterFlow = createFlow([flowHola, flowAdios, flowProductos, flowCatalogo])
const adapterProvider = createProvider(BaileysProvider)
createBot({
flow: adapterFlow,
provider: adapterProvider,
database: adapterDB,
})
}
```
#### Flujos hijos
A continuación se muestra un ejemplo de flujos hijos, estos nos sirven para crear flujos que solo se disparan cuando el flujo anterior es el especificado, ejemplo:
> Menu Principal (Escoge zapatos o bolsos)
> - SubMenu 1 (Elegiste bolsos, ahora escoge piel o tela)
> - Submenu 1.1 (piel)
> - Submenu 2 (Elegiste zapatos, ahora escoge piel o tela)
> - Submenu 2.1 (piel)
El __submenu 1__ solo se va a disparar cuando el flujo anterior sea el __principal__, e igualmente el __submenu 1.1__, solo cuando el flujo anterior sea el __submenu 1__, ejemplo:
```js
/**
* Aqui declaramos los flujos hijos, los flujos se declaran de atras para adelante, es decir que si tienes un flujo de este tipo:
*
* Menu Principal
* - SubMenu 1
* - Submenu 1.1
* - Submenu 2
* - Submenu 2.1
*
* Primero declaras los submenus 1.1 y 2.1, luego el 1 y 2 y al final el principal.
*/
const flowBolsos2 = addKeyword(['bolsos2', '2'])
.addAnswer('🤯 *MUCHOS* bolsos ...')
.addAnswer('y mas bolsos... bla bla')
const flowZapatos2 = addKeyword(['zapatos2', '2'])
.addAnswer('🤯 repito que tengo *MUCHOS* zapatos.')
.addAnswer('y algunas otras cosas.')
const flowZapatos = addKeyword(['1', 'zapatos', 'ZAPATOS'])
.addAnswer('🤯 Veo que elegiste zapatos')
.addAnswer('Tengo muchos zapatos...bla bla')
.addAnswer(
['Manda:', '*(2) Zapatos2*', 'para mas información'],
{ capture: true },
(ctx) => {
console.log('Aqui puedes ver más info del usuario...')
console.log('Puedes enviar un mail, hook, etc..')
console.log(ctx)
},
[...addChild(flowZapatos2)]
)
const flowBolsos = addKeyword(['2', 'bolsos', 'BOLSOS'])
.addAnswer('🙌 Veo que elegiste bolsos')
.addAnswer('Tengo muchos bolsos...bla bla')
.addAnswer(
['Manda:', '*(2) Bolsos2*', 'para mas información.'],
{ capture: true },
(ctx) => {
console.log('Aqui puedes ver más info del usuario...')
console.log('Puedes enviar un mail, hook, etc..')
console.log(ctx)
},
[...addChild(flowBolsos2)]
)
/**
* Declarando flujo principal
*/
const flowPrincipal = addKeyword(['hola', 'ole', 'alo'])
.addAnswer(['Hola, bienvenido a mi tienda', '¿Como puedo ayudarte?'])
.addAnswer(['Tengo:', 'Zapatos', 'Bolsos', 'etc ...'])
.addAnswer(
['Para continuar escribe:', '*(1) Zapatos*', '*(2) Bolsos*'],
{ capture: true },
(ctx) => {
console.log('Aqui puedes ver más info del usuario...')
console.log('Puedes enviar un mail, hook, etc..')
console.log(ctx)
},
[...addChild(flowBolsos), ...addChild(flowZapatos)]
)
```
> Forma parte de este proyecto.
- [Discord](https://link.codigoencasa.com/DISCORD)
- [Twitter](https://twitter.com/leifermendez)
- [Youtube](https://www.youtube.com/watch?v=5lEMCeWEJ8o&list=PL_WGMLcL4jzWPhdhcUyhbFU6bC0oJd2BR)
- [Telegram](https://t.me/leifermendez)

234
README.md
View File

@@ -1,116 +1,118 @@
## Chatbot Whatsapp (OpenSource)
#### Actualización
| Feature | Status |
| ------------- | ------------- |
| Dialogflow | ✅ |
| MySQL | ✅ |
| JSON File | ✅ |
| QR Scan (route) | ✅ |
| Easy deploy heroku | ✅ |
| Buttons | ✅ℹ️ (No funciona en multi-device)|
| Send Voice Note | ✅ |
| Add support ubuntu/linux | ✅ |
## Requisitos
- node v14 o superior
- VSCode (Editor de codigo) [Descargar](https://code.visualstudio.com/download)
- MySql (opcional) solo aplica si vas a usar el modo 'mysql' [sql-bot.sql migración](https://github.com/leifermendez/bot-whatsapp/blob/main/sql-bot.sql)
- Dialogflow (opcional) solo aplica si vas a usar el modo 'dialogflow'
### (Nuevo) Botones
[![btn](https://i.imgur.com/W7oYlSu.png)](https://youtu.be/5lEMCeWEJ8o)
> Implementar los botones solo necesitas hacer uso del metodo __sendMessageButton__ que se encuentra dentro `./controllers/send` dejo un ejemplo de como usarlo.
[Ver implementación](https://github.com/leifermendez/bot-whatsapp/blob/main/app.js#L123)
``` javascript
const { sendMessageButton } = require('./controllers/send')
await sendMessageButton(
{
"title":"¿Que te interesa ver?",
"message":"Recuerda todo este contenido es gratis y estaria genial que me siguas!",
"footer":"Gracias",
"buttons":[
{"body":"😎 Cursos"},
{"body":"👉 Youtube"},
{"body":"😁 Telegram"}
]
}
)
```
## Notas de Voz
[![voice note](https://i.imgur.com/zq6xYDp.png)](https://i.imgur.com/zq6xYDp.png)
> Se pueden enviar notas de voz con formato nativo para que no se vea como reenviado. En este ejemplo enviare el archivo __PTT-20220223-WA0000.opus__ que se encuentra dentro de la carpeta de __/mediaSend__
``` javascript
const { sendMediaVoiceNote } = require('./controllers/send')
await sendMediaVoiceNote(client, from, 'PTT-20220223-WA0000.opus')
```
## Instruciones
__Descargar o Clonar repositorio__
__Usas ¿Ubuntu / Linux?__
> Asegurate de instalar los siguientes paquetes
```
sudo apt-get install -y libgbm-dev
sudo apt install -y gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget
```
__Instalar dependencias (npm install)__
> Ubicate en le directorio que descargaste y via consola o terminal ejecuta el siguiente comando
```
npm i
```
__Configurar .env__
> Con el editor de texto crea un archivo `.env` el cual debes de guiarte del archivo `.env.example`
[Ver video explicando](https://youtu.be/5lEMCeWEJ8o?t=381)
```
######DATABASE: none, mysql, dialogflow
DEFAULT_MESSAGE=true
SAVE_MEDIA=true
PORT=3000
DATABASE=none
LANGUAGE=es
SQL_HOST=
SQL_USER=
SQL_PASS=
SQL_DATABASE=
```
__Ejecutar el script__
> Ubicate en le directorio que descargaste y via consola o terminal ejecuta el siguiente comando
`npm run start`
__Whatsapp en tu celular__
> 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" />
Tambien puedes visitar la pagina http://127.0.0.1:3000/qr
__Listo 😎__
> Cuando sale este mensaje tu BOT está __listo__ para trabajar!
![](https://i.imgur.com/eoJ4Ruk.png)
# ¿Quieres ver como se creó? 🤖
- [Ver Video 1](https://www.youtube.com/watch?v=A_Xu0OR_HkE)
- [¿Como instalarlo? (Actulización)](https://youtu.be/5lEMCeWEJ8o)
## ¿Como usarlo el chatbot de whatsapp?
> Escribe un mensaje al whatsapp que vinculaste con tu BOT
![](https://i.imgur.com/OSUgljQ.png)
> 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
# Chatbot Library
![](https://img.shields.io/npm/v/@bot-whatsapp/bot?color=%2300c200&label=%40bot-whatsapp)
[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
[![BotWhatsapp Releases(Prod)](https://github.com/codigoencasa/bot-whatsapp/actions/workflows/releases.yml/badge.svg)](https://github.com/codigoencasa/bot-whatsapp/actions/workflows/releases.yml)
<p align="center">
<img width="300" src="https://i.imgur.com/Oauef6t.png">
</p>
**Con esta librería, puedes construir flujos automatizados de conversación de manera agnóstica al proveedor de WhatsApp,** configurar respuestas automatizadas para preguntas frecuentes, recibir y responder mensajes de manera automatizada, y hacer un seguimiento de las interacciones con los clientes.  Además, puedes configurar fácilmente disparadores que te ayudaran a expandir las funcionalidades sin límites. **[Ver más informacion](https://bot-whatsapp.netlify.app/)**
## Comenzar
```
npm create bot-whatsapp@latest
```
Entiende más a fondo sus funcionalidades explicadas en nuestra documentación.
- Instalacion
- Base de datos
- Proveedores
## Recursos
- [📄 Documentación](https://bot-whatsapp.netlify.app/)
- [🚀 Roadmap](https://github.com/orgs/codigoencasa/projects/1)
- [💻 Discord](https://link.codigoencasa.com/DISCORD)
- [👌 Twitter](https://twitter.com/leifermendez)
- [🎥 Youtube](https://www.youtube.com/watch?v=5lEMCeWEJ8o&list=PL_WGMLcL4jzWPhdhcUyhbFU6bC0oJd2BR)
## Comunidad
<!-- readme: collaborators,contributors -start -->
<table>
<tr>
<td align="center">
<a href="https://github.com/leifermendez">
<img src="https://avatars.githubusercontent.com/u/15802366?v=4" width="50;" alt="leifermendez"/>
<br />
<sub><b>Leifer Mendez</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/aurik3">
<img src="https://avatars.githubusercontent.com/u/37228512?v=4" width="50;" alt="aurik3"/>
<br />
<sub><b>Null</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/vicente1992">
<img src="https://avatars.githubusercontent.com/u/57806030?v=4" width="50;" alt="vicente1992"/>
<br />
<sub><b>Manuel Vicente Ortiz</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/leifermendezfroged">
<img src="https://avatars.githubusercontent.com/u/97020486?v=4" width="50;" alt="leifermendezfroged"/>
<br />
<sub><b>Leifer Mendez</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/HKong31">
<img src="https://avatars.githubusercontent.com/u/113340082?v=4" width="50;" alt="HKong31"/>
<br />
<sub><b>HLKong</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/jzvi12">
<img src="https://avatars.githubusercontent.com/u/10729787?v=4" width="50;" alt="jzvi12"/>
<br />
<sub><b>Zvi</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/Gonzalito87">
<img src="https://avatars.githubusercontent.com/u/100331586?v=4" width="50;" alt="Gonzalito87"/>
<br />
<sub><b>Null</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/tonyvazgar">
<img src="https://avatars.githubusercontent.com/u/21047090?v=4" width="50;" alt="tonyvazgar"/>
<br />
<sub><b>Luis Antonio Vázquez García</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/ulisesvina">
<img src="https://avatars.githubusercontent.com/u/20508563?v=4" width="50;" alt="ulisesvina"/>
<br />
<sub><b>Ulises Viña</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/rrruuuyyy">
<img src="https://avatars.githubusercontent.com/u/33061671?v=4" width="50;" alt="rrruuuyyy"/>
<br />
<sub><b>Rodrigo Mendoza Cabrera</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/yond1994">
<img src="https://avatars.githubusercontent.com/u/47557263?v=4" width="50;" alt="yond1994"/>
<br />
<sub><b>Yonathan Suarez</b></sub>
</a>
</td></tr>
</table>
<!-- readme: collaborators,contributors -end -->

51
TODO.md Normal file
View File

@@ -0,0 +1,51 @@
### Genral
- [X] __(doc)__ Video de como colaborar PR
- [ ] __(doc)__ Video implementación de test y cobertura
- [ ] __(doc)__ Video explicacion de github action
- [ ] Crear packages list externas
### @bot-whatsapp/bot
- [X] agregar export package
- [X] Posibilidad de en el capture meter todo un nuevo CTX de FLOW .addAnswer('Marca la opcion',{capture:true, join:CTX})
- [X] .addKeyword('1') no funciona con 1 caracter
- [X] sensitivy viene activado por defecto
- [X] fallback respuesta en hijo: Se puede colocar en option el ref de la answer fallback
- [X] Cuando Envian Sticket devuelve mensaje raro
- [x] addAnswer agregar delay
- [ ] colocar mensaje esperando conectando whatsapp (provider)
- [ ] createDatabase validar implementacion de funciones
- [ ] limitar caracteres de mensajes 4000
- [X] cuando envias numeros (5 o 1) se dispara el flujo
### @bot-whatsapp/database
- [X] agregar export package
- [X] __(doc):__ Video para explicar como implementar nuevos database
- [X] Mongo adapter
- [X] MySQL adapter
- [ ] JsonFile adapter
### @bot-whatsapp/provider
- [X] agregar export package
- [ ] __(doc):__ Video para explicar como implementar nuevos providers
- [X] WhatsappWeb provider enviar imagenes
- [X] WhatsappWeb provider enviar audio
- [X] WhatsappWeb botones (Tiene truco) github:leifermendez/whatsapp-web.js
- [ ] Twilio adapter
- [ ] Meta adapter
### @bot-whatsapp/cli
- [X] Hacer comando para crear `example-app`
### @bot-whatsapp/create-bot
- [ ]
### Starters
- [X] Base
- [X] Basico
- [ ] Enviando Imagen
- [ ] Enviando Botones
- [ ] Mezclando flujos hijos
### Extra
- [X] Crear CI mantener fork update https://stackoverflow.com/questions/23793062/can-forks-be-synced-automatically-in-github

6
__mocks__/mobile.mock.js Normal file
View File

@@ -0,0 +1,6 @@
const MOCK_MOBILE_WS = {
from: 'XXXXXX',
hasMedia: false,
}
module.exports = { MOCK_MOBILE_WS }

View File

@@ -0,0 +1,21 @@
const ProviderClass = require('../packages/bot/provider/provider.class')
class MockProvider extends ProviderClass {
constructor() {
super()
}
delaySendMessage = (miliseconds, eventName, payload) =>
new Promise((res) =>
setTimeout(() => {
this.emit(eventName, payload)
res
}, miliseconds)
)
sendMessage = async (userId, message) => {
console.log(`Enviando... ${userId}, ${message}`)
return Promise.resolve({ userId, message })
}
}
module.exports = MockProvider

View File

@@ -1,81 +0,0 @@
const dialogflow = require('@google-cloud/dialogflow');
const fs = require('fs')
const {struct} = require('pb-util');
/**
* Debes de tener tu archivo con el nombre "chatbot-account.json" en la raíz del proyecto
*/
const KEEP_DIALOG_FLOW = (process.env.KEEP_DIALOG_FLOW === 'true')
let PROJECID;
let CONFIGURATION;
let sessionClient;
const checkFileCredentials = () => {
if(!fs.existsSync(`${__dirname}/../chatbot-account.json`)){
return false
}
const parseCredentials = JSON.parse(fs.readFileSync(`${__dirname}/../chatbot-account.json`));
PROJECID = parseCredentials.project_id;
CONFIGURATION = {
credentials: {
private_key: parseCredentials['private_key'],
client_email: parseCredentials['client_email']
}
}
sessionClient = new dialogflow.SessionsClient(CONFIGURATION);
}
// Create a new session
// Detect intent method
const detectIntent = async (queryText, waPhoneNumber) => {
let media = null;
let actions = null;
const sessionId = KEEP_DIALOG_FLOW ? 1 : waPhoneNumber;
const sessionPath = sessionClient.projectAgentSessionPath(PROJECID, sessionId);
const languageCode = process.env.LANGUAGE
const request = {
session: sessionPath,
queryInput: {
text: {
text: queryText,
languageCode: languageCode,
},
},
};
const responses = await sessionClient.detectIntent(request);
const [singleResponse] = responses;
const { queryResult } = singleResponse
const { intent } = queryResult || { intent: {} }
const parseIntent = intent['displayName'] || null
const parsePayload = queryResult['fulfillmentMessages'].find((a) => a.message === 'payload');
// console.log(singleResponse)
if (parsePayload && parsePayload.payload) {
const { fields } = parsePayload.payload
actions = struct.decode(fields.actions.structValue) || null;
media = fields.media.stringValue || null
}
const customPayload = parsePayload ? parsePayload['payload'] : null
const parseData = {
replyMessage: queryResult.fulfillmentText,
media,
actions,
trigger: null
}
return parseData
}
const getDataIa = (message = '', sessionId = '', cb = () => { }) => {
detectIntent(message, sessionId).then((res) => {
cb(res)
})
}
checkFileCredentials();
module.exports = { getDataIa }

View File

@@ -1,103 +0,0 @@
require('dotenv').config({ path: `${__dirname}/../.env` });
const { google } = require('googleapis');
const path = require('path');
const fs = require('fs');
//const clientEmail = require(`${__dirname}/../chatbot-account.json`);
/**
* La funcion 'generatePublicUrl' genera un error muy menor al enviar el 'requestBody'
* siempre y cuando necesites que el acceso sea restringido y solo ciertos usuarios puedan acceder.
* Esto se logra con la combinacion requerida: 'reader', 'user' y 'emailAddress':
* requestBody: {
* role: 'reader',
* type: 'user',
* emailAddress: usuario@gmail.com,
* },
* Segun la documentacion https://developers.google.com/drive/api/v3/reference/permissions/create#request-body,
* los datos se envian correctamente, pero la respuesta del API regresa este error:
* Bad Request. User message: "You cannot share this item because it has been flagged as inappropriate."
* Al parecer, es un error conocido en stackoverflow.com entre varios usuarios del API.
*/
if (process.env.DATABASE === 'dialogflow') {
/**
* Debes de tener tu archivo con el nombre "chatbot-account.json" en la raíz del proyecto
*/
const KEYFILEPATH = path.join(`${__dirname}/../chatbot-account.json`);
const SCOPES = ['https://www.googleapis.com/auth/drive'];
const auth = new google.auth.GoogleAuth({
keyFile: KEYFILEPATH,
scopes: SCOPES,
});
const drive = google.drive({
version: 'v3',
auth,
});
const uploadSingleFile = async (fileName, filePath) => {
const folderId = process.env.GDRIVE_FOLDER_ID;
const { data: { id, name } = {} } = await drive.files.create({
resource: {
name: fileName,
parents: [folderId],
},
media: {
mimeType: 'image/jpg',
body: fs.createReadStream(filePath),
},
fields: 'id,name',
});
generatePublicUrl(id).then(() => {
console.log(`Se generó enlace https://drive.google.com/open?id=${id} para el archivo ${name}`);
});
return `https://drive.google.com/open?id=${id}`
};
const scanFolderForFiles = async (folderPath) => {
const folder = await fs.promises.opendir(folderPath);
for await (const dirent of folder) {
if (dirent.isFile() && dirent.name.endsWith('.jpeg')) {
await uploadSingleFile(dirent.name, path.join(folderPath, dirent.name));
await fs.promises.rm(filePath);
}
}
};
async function generatePublicUrl(id) {
try {
const fileId = id;
await drive.permissions.create({
fileId: fileId,
supportsAllDrives: true,
requestBody: {
role: 'reader',
type: 'domain', // 'anyone' da acceso al publico vía enlace https://drive.google.com...
domain: 'gserviceaccount.com', // Si tu cuenta esta bajo un dominio (usuario@empresa.com) y no bajo gmail.com
allowFileDiscovery: false,
},
});
/*
webViewLink: Ver el archivo en el navegador
webContentLink: Enlace de descarga directa
*/
const result = await drive.files.get({
fileId: fileId,
fields: 'webViewLink, webContentLink',
});
console.log(result.data);
} catch (error) {
//console.log(error.message); // Imprime 'Internal Error', pero aún así genera el enlace
console.error = () => { }; // No muestra el error anterior
}
}
module.exports = { uploadSingleFile, scanFolderForFiles }
} else {
console.log(`Actualmente, la base de datos es:\n\t'DATABASE=${process.env.DATABASE}'\nPara usar Google Drive, cambiar a:\n\t'DATABASE=dialogflow'`);
}

View File

@@ -1,90 +0,0 @@
const { getData, getReply, saveMessageMysql } = require('./mysql')
const { saveMessageJson } = require('./jsonDb')
const { getDataIa } = require('./diaglogflow')
const stepsInitial = require('../flow/initial.json')
const stepsReponse = require('../flow/response.json')
const get = (message) => new Promise((resolve, reject) => {
/**
* Si no estas usando un gesto de base de datos
*/
if (process.env.DATABASE === 'none') {
const { key } = stepsInitial.find(k => k.keywords.includes(message)) || { key: null }
const response = key || null
resolve(response)
}
/**
* Si usas MYSQL
*/
if (process.env.DATABASE === 'mysql') {
getData(message, (dt) => {
resolve(dt)
});
}
})
const reply = (step) => new Promise((resolve, reject) => {
/**
* Si no estas usando un gesto de base de datos
*/
if (process.env.DATABASE === 'none') {
let resData = { replyMessage: '', media: null, trigger: null }
const responseFind = stepsReponse[step] || {};
resData = {
...resData,
...responseFind,
replyMessage:responseFind.replyMessage.join('')}
resolve(resData);
return
}
/**
* Si usas MYSQL
*/
if (process.env.DATABASE === 'mysql') {
let resData = { replyMessage: '', media: null, trigger: null }
getReply(step, (dt) => {
resData = { ...resData, ...dt }
resolve(resData)
});
}
})
const getIA = (message, sessionId) => new Promise((resolve, reject) => {
/**
* Si usas dialogflow
*/
if (process.env.DATABASE === 'dialogflow') {
let resData = { replyMessage: '', media: null, trigger: null }
getDataIa(message, sessionId, (dt) => {
resData = { ...resData, ...dt }
resolve(resData)
})
}
})
/**
*
* @param {*} message
* @param {*} date
* @param {*} trigger
* @param {*} number
* @returns
*/
const saveMessage = ( message, trigger, number ) => new Promise( async (resolve, reject) => {
switch ( process.env.DATABASE ) {
case 'mysql':
resolve( await saveMessageMysql( message, trigger, number ) )
break;
case 'none':
resolve( await saveMessageJson( message, trigger, number ) )
break;
default:
resolve(true)
break;
}
})
module.exports = { get, reply, getIA, saveMessage }

View File

@@ -1,20 +0,0 @@
const Path = require('path')
const StormDB = require("stormdb");
const date = new Date().toISOString();
const saveMessageJson = (message, trigger, number) => new Promise( async(resolve,reject) =>{
try {
const engine = new StormDB.localFileEngine( Path.join(__dirname, `/../chats/${number}.json`) );
const db = new StormDB(engine);
// set default db value if db is empty
db.default({ messages: [] });
// add new users entry
db.get("messages").push({ message, date, trigger });
db.save();
resolve('Saved')
} catch (error) {
console.log(error)
reject(error)
}
})
module.exports = { saveMessageJson }

View File

@@ -1,74 +0,0 @@
const {connection} = require('../config/mysql')
const DATABASE_NAME = process.env.SQL_DATABASE || 'db_test'
getData = (message = '', callback) => connection.query(
`SELECT * FROM ${DATABASE_NAME}.initial WHERE keywords LIKE '%${message}%' LIMIT 1`,
(error, results
) => {
const [response] = results
const key = response?.option_key || null
callback(key)
});
getReply = (option_key = '', callback) => connection.query(
`SELECT * FROM ${DATABASE_NAME}.response WHERE option_key = '${option_key}' LIMIT 1`,
(error, results
) => {
const [response] = results;
console.log(response)
const value = {
replyMessage:response?.replyMessage || '',
trigger:response?.trigger || '',
media:response?.media || ''
}
callback(value)
});
getMessages = ( number ) => new Promise((resolve,reejct) => {
try {
connection.query(
`SELECT * FROM ${DATABASE_NAME}.response WHERE number = '${number}'`, (error, results) => {
if(error) {
console.log(error)
}
const [response] = results;
console.log(response)
const value = {
replyMessage:response?.replyMessage || '',
trigger:response?.trigger || '',
media:response?.media || ''
}
resolve(value)
})
} catch (error) {
}
})
saveMessageMysql = ( message, date, trigger, number ) => new Promise((resolve,reejct) => {
try {
connection.query(
`INSERT INTO ${DATABASE_NAME}.messages `+"( `message`, `date`, `trigger`, `number`)"+` VALUES ('${message}','${date}','${trigger}', '${number}')` , (error, results) => {
if(error) {
//TODO esta parte es mejor incluirla directamente en el archivo .sql template
console.log('DEBES DE CREAR LA TABLA DE MESSAGE')
// if( error.code === 'ER_NO_SUCH_TABLE' ){
// connection.query( `CREATE TABLE ${DATABASE_NAME}.messages `+"( `date` DATE NOT NULL , `message` VARCHAR(450) NOT NULL , `trigger` VARCHAR(450) NOT NULL , `number` VARCHAR(50) NOT NULL ) ENGINE = InnoDB", async (error, results) => {
// setTimeout( async () => {
// return resolve( await this.saveMessageMysql( message, date, trigger, number ) )
// }, 150)
// })
// }
}
console.log('Saved')
console.log( results )
resolve(results)
})
} catch (error) {
}
})
module.exports = {getData, getReply, saveMessageMysql}

209
app.js
View File

@@ -1,209 +0,0 @@
/**
* ⚡⚡⚡ DECLARAMOS LAS LIBRERIAS y CONSTANTES A USAR! ⚡⚡⚡
*/
require('dotenv').config()
const fs = require('fs');
const express = require('express');
const cors = require('cors')
const qrcode = require('qrcode-terminal');
const { Client, LocalAuth } = require('whatsapp-web.js');
const mysqlConnection = require('./config/mysql')
const { middlewareClient } = require('./middleware/client')
const { generateImage, cleanNumber, checkEnvFile, createClient, isValidNumber } = require('./controllers/handle')
const { connectionReady, connectionLost } = require('./controllers/connection')
const { saveMedia, saveMediaToGoogleDrive } = require('./controllers/save')
const { getMessages, responseMessages, bothResponse, waitFor } = require('./controllers/flows')
const { sendMedia, sendMessage, lastTrigger, sendMessageButton, readChat } = require('./controllers/send')
const app = express();
app.use(cors())
app.use(express.json())
const MULTI_DEVICE = process.env.MULTI_DEVICE || 'true';
const server = require('http').Server(app)
const port = process.env.PORT || 3000
var client;
var dialogflowFilter = false;
app.use('/', require('./routes/web'))
/**
* Escuchamos cuando entre un mensaje
*/
const listenMessage = () => client.on('message', async msg => {
const { from, body, hasMedia } = msg;
if (!isValidNumber(from)) {
return
}
// Este bug lo reporto Lucas Aldeco Brescia para evitar que se publiquen estados
if (from === 'status@broadcast') {
return
}
message = body.toLowerCase();
console.log('BODY', message)
const number = cleanNumber(from)
await readChat(number, message)
/**
* Guardamos el archivo multimedia que envia
*/
if (process.env.SAVE_MEDIA === 'true' && hasMedia) {
const media = await msg.downloadMedia();
saveMedia(media);
}
/**
* Si estas usando dialogflow solo manejamos una funcion todo es IA
*/
if (process.env.DATABASE === 'dialogflow') {
if (process.env.DIALOGFLOW_MEDIA_FOR_SLOT_FILLING === 'true' && dialogflowFilter) {
waitFor(_ => hasMedia, 30000)
.then(async _ => {
if (hasMedia) {
const media = await msg.downloadMedia();
message = await saveMediaToGoogleDrive(media);
const response = await bothResponse(message.substring(256, -1), number);
await sendMessage(client, from, response.replyMessage);
}
return
});
dialogflowFilter = false;
}
if (!message.length) return;
const response = await bothResponse(message.substring(256, -1), number);
await sendMessage(client, from, response.replyMessage);
if (response.actions) {
await sendMessageButton(client, from, null, response.actions);
return
}
if (response.media) {
sendMedia(client, from, response.media);
}
return
}
/**
* Ver si viene de un paso anterior
* Aqui podemos ir agregando más pasos
* a tu gusto!
*/
const lastStep = await lastTrigger(from) || null;
if (lastStep) {
const response = await responseMessages(lastStep)
await sendMessage(client, from, response.replyMessage);
}
/**
* Respondemos al primero paso si encuentra palabras clave
*/
const step = await getMessages(message);
if (step) {
const response = await responseMessages(step);
/**
* Si quieres enviar botones
*/
await sendMessage(client, from, response.replyMessage, response.trigger);
if (response.hasOwnProperty('actions')) {
const { actions } = response;
await sendMessageButton(client, from, null, actions);
return
}
if (!response.delay && response.media) {
sendMedia(client, from, response.media);
}
if (response.delay && response.media) {
setTimeout(() => {
sendMedia(client, from, response.media);
}, response.delay)
}
return
}
//Si quieres tener un mensaje por defecto
if (process.env.DEFAULT_MESSAGE === 'true') {
const response = await responseMessages('DEFAULT')
await sendMessage(client, from, response.replyMessage, response.trigger);
/**
* Si quieres enviar botones
*/
if (response.hasOwnProperty('actions')) {
const { actions } = response;
await sendMessageButton(client, from, null, actions);
}
return
}
});
/**
* Este evento es necesario para el filtro de Dialogflow
*/
const listenMessageFromBot = () => client.on('message_create', async botMsg => {
const { body } = botMsg;
const dialogflowFilterConfig = fs.readFileSync('./flow/dialogflow.json', 'utf8');
const keywords = JSON.parse(dialogflowFilterConfig);
for (i = 0; i < keywords.length; i++) {
key = keywords[i];
for (var j = 0; j < key.phrases.length; j++) {
let filters = key.phrases[j];
if (body.includes(filters)) {
dialogflowFilter = true;
//console.log(`El filtro de Dialogflow coincidió con el mensaje: ${filters}`);
}
}
}
});
client = new Client({
authStrategy: new LocalAuth(),
puppeteer: { headless: true }
});
client.on('qr', qr => generateImage(qr, () => {
qrcode.generate(qr, { small: true });
console.log(`Ver QR http://localhost:${port}/qr`)
socketEvents.sendQR(qr)
}))
client.on('ready', (a) => {
connectionReady()
listenMessage()
listenMessageFromBot()
// socketEvents.sendStatus(client)
});
client.on('auth_failure', (e) => {
// console.log(e)
// connectionLost()
});
client.on('authenticated', () => {
console.log('AUTHENTICATED');
});
client.initialize();
/**
* Verificamos si tienes un gesto de db
*/
if (process.env.DATABASE === 'mysql') {
mysqlConnection.connect()
}
server.listen(port, () => {
console.log(`El server esta listo por el puerto ${port}`);
})
checkEnvFile();

View File

@@ -1,35 +0,0 @@
{
"name": "Chatbot Whatsapp (Leifer Mendez)",
"description": "El siguiente proyecto se realizó con fines educativos para el canal de Youtube (Leifer Mendez) donde aprendemos como usando node.js podemos crear un chatbot increíble que además le agregamos inteligencia artificial gracias al servicio de dialogflow",
"repository": "https://github.com/leifermendez/bot-whatsapp",
"logo": "https://avatars0.githubusercontent.com/u/15802366?s=460&u=77ec7ef359e8ed842aef769693f1675c0ed460fd&v=4",
"keywords": [
"nodejs",
"whatsapp",
"bot",
"chatbot",
"dialogflow"
],
"addons": [
],
"buildpacks": [
{
"url": "heroku/nodejs"
},
{
"url": "https://github.com/jontewks/puppeteer-heroku-buildpack"
}
],
"env": {
"SAVE_MEDIA": "false",
"DATABASE": {
"description": "'none', 'mysql', 'dialogflow' por defecto 'none' Puedes usar alguna de los siguientes opciones. Pero antes debes de saber como funciona y eso lo explico en el video. Puedes obtener más información https://github.com/leifermendez/bot-whatsapp/blob/main/README.md",
"value": "none"
},
"LANGUAGE": "es",
"SQL_HOST":"your_host",
"SQL_USER":"your_user",
"SQL_PASS":"your_password",
"SQL_DATABASE":"your_database"
}
}

91
changelog.config.js Normal file
View File

@@ -0,0 +1,91 @@
module.exports = {
disableEmoji: false,
format: '{type}{scope}: {emoji}{subject}',
list: [
'test',
'feat',
'fix',
'chore',
'docs',
'refactor',
'style',
'ci',
'perf',
],
maxMessageLength: 64,
minMessageLength: 3,
questions: [
'type',
'scope',
'subject',
'body',
'breaking',
'issues',
'lerna',
],
scopes: [],
types: {
chore: {
description: 'Build process or auxiliary tool changes',
emoji: '(🤖)',
value: 'chore',
},
ci: {
description: 'CI related changes',
emoji: '(🎡)',
value: 'ci',
},
docs: {
description: 'Documentation only changes',
emoji: '(✏️)',
value: 'docs',
},
feat: {
description: 'A new feature',
emoji: '(🎸)',
value: 'feat',
},
fix: {
description: 'A bug fix',
emoji: '(🐛)',
value: 'fix',
},
perf: {
description: 'A code change that improves performance',
emoji: '(⚡️)',
value: 'perf',
},
refactor: {
description:
'A code change that neither fixes a bug or adds a feature',
emoji: '(💡)',
value: 'refactor',
},
release: {
description: 'Create a release commit',
emoji: '(🏹)',
value: 'release',
},
style: {
description:
'Markup, white-space, formatting, missing semi-colons...',
emoji: '(💄)',
value: 'style',
},
test: {
description: 'Adding missing tests',
emoji: '(💍)',
value: 'test',
},
messages: {
type: "Select the type of change that you're committing:",
customScope: 'Select the scope this component affects:',
subject:
'Write a short, imperative mood description of the change:\n',
body: 'Provide a longer description of the change:\n ',
breaking: 'List any breaking changes:\n',
footer: 'Issues this commit closes, e.g #123:',
confirmCommit: 'The packages that this commit has affected\n',
},
},
}

View File

@@ -1,13 +0,0 @@
{
"type": "",
"project_id": "",
"private_key_id": "",
"private_key":"",
"client_email": "",
"client_id": "",
"auth_uri": "",
"token_uri": "",
"auth_provider_x509_cert_url": "",
"client_x509_cert_url":""
}

1
commitlint.config.js Normal file
View File

@@ -0,0 +1 @@
module.exports = { extends: ['@commitlint/config-conventional'] }

View File

@@ -0,0 +1,8 @@
{
"banner.output": [
"/** \n",
"* NO TOCAR ESTE ARCHIVO: Es generado automaticamente, si sabes lo que haces adelante ;)\n",
"* de lo contrario mejor ir a la documentacion o al servidor de discord link.codigoencasa.com/DISCORD\n",
"*/"
]
}

View File

@@ -1,18 +0,0 @@
const mysql = require('mysql');
const connection = mysql.createConnection({
host : process.env.SQL_HOST || 'localhost',
user : process.env.SQL_USER || 'root',
password : process.env.SQL_PASS || '',
database : process.env.SQL_DATABASE || 'pruebas'
});
const connect = () => connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('Conexion correcta con tu base de datos MySQL')
});
module.exports = {connect, connection}

View File

@@ -1,14 +0,0 @@
const connectionReady = (cb = () =>{}) => {
console.log('Listo para escuchas mensajes')
console.log('Client is ready!');
console.log('🔴 escribe: hola');
cb()
}
const connectionLost = (cb = () =>{}) => {
console.log('** Error de autentificacion vuelve a generar el QRCODE (Borrar el archivo session.json) **');
cb()
}
module.exports = {connectionReady, connectionLost}

View File

@@ -1,36 +0,0 @@
const { get, reply, getIA } = require('../adapter')
const { saveExternalFile, checkIsUrl } = require('./handle')
const getMessages = async (message) => {
const data = await get(message)
return data
}
const responseMessages = async (step) => {
const data = await reply(step)
if (data && data.media) {
const file = checkIsUrl(data.media) ? await saveExternalFile(data.media) : data.media;
return { ...data, ...{ media: file } }
}
return data
}
const bothResponse = async (message, sessionId) => {
const data = await getIA(message, sessionId)
if (data && data.media) {
const file = await saveExternalFile(data.media)
return { ...data, ...{ media: file } }
}
return data
}
const waitFor = (conditionFunction, WAIT_TIME) => {
const poll = resolve => {
if (conditionFunction())
resolve();
else setTimeout(_ => poll(resolve), WAIT_TIME);
}
return new Promise(poll);
}
module.exports = { getMessages, responseMessages, bothResponse, waitFor }

View File

@@ -1,83 +0,0 @@
const { Client, LegacySessionAuth, LocalAuth } = require('whatsapp-web.js');
const http = require('http'); // or 'https' for https:// URLs
const https = require('https'); // or 'https' for https:// URLs
const fs = require('fs');
const qr = require('qr-image')
const MULTI_DEVICE = process.env.MULTI_DEVICE || 'true';
const cleanNumber = (number) => {
number = number.replace('@c.us', '');
number = `${number}@c.us`;
return number
}
const saveExternalFile = (url) => new Promise((resolve, reject) => {
const ext = url.split('.').pop()
const checkProtocol = url.split('/').includes('https:');
const handleHttp = checkProtocol ? https : http;
const name = `${Date.now()}.${ext}`;
const file = fs.createWriteStream(`${__dirname}/../mediaSend/${name}`);
console.log(url)
handleHttp.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(); // close() is async, call cb after close completes.
resolve(name)
});
file.on('error', function() {
console.log('errro')
file.close(); // close() is async, call cb after close completes.
resolve(null)
});
});
})
const checkIsUrl = (path) => {
try{
regex = /^(http(s)?:\/\/)[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/i;
match = path.match(regex);
return match[0]
}catch(e){
return null
}
}
const generateImage = (base64, cb = () => {}) => {
let qr_svg = qr.image(base64, { type: 'svg', margin: 4 });
qr_svg.pipe(require('fs').createWriteStream('./mediaSend/qr-code.svg'));
console.log(`⚡ Recuerda que el QR se actualiza cada minuto ⚡'`);
console.log(`⚡ Actualiza F5 el navegador para mantener el mejor QR⚡`);
cb()
}
const checkEnvFile = () => {
const pathEnv = `${__dirname}/../.env`;
const isExist = fs.existsSync(pathEnv);
if(!isExist){
console.log(`🆗 ATENCION! 🆗 te falta crear tu archivo .env de lo contrario no funcionara`)
}
}
/**
*
* @param {*} session
* @param {*} cb
*/
const createClient = () => {
client = new Client({
authStrategy: new LocalAuth(
{dataPath: './sessions/',
clientId: 'bot'}),
puppeteer: { headless: false }
});
}
const isValidNumber = (rawNumber) => {
const regexGroup = /\@g.us\b/gm;
const exist = rawNumber.match(regexGroup);
return !exist
}
module.exports = {cleanNumber, saveExternalFile, generateImage, checkIsUrl, checkEnvFile, createClient, isValidNumber}

View File

@@ -1,38 +0,0 @@
const mimeDb = require('mime-db');
const { uploadSingleFile } = require('../adapter/gdrive');
const fs = require('fs');
var fileName;
/**
* Guardamos archivos multimedia que nuestro cliente nos envie!
* @param {*} media
*/
const saveMedia = (media) => {
const extensionProcess = mimeDb[media.mimetype];
let ext;
if (!extensionProcess) {
const fileType = media.mimetype.split('/');
ext = fileType[1].split(';')[0];
} else {
ext = extensionProcess.extensions[0];
}
fileName = `${Date.now()}.${ext}`;
fs.writeFile(`./media/${fileName}`, media.data, { encoding: 'base64' }, function (err) {
console.log(`** Archivo Media ${fileName} Guardado **`);
});
return fileName
}
const saveMediaToGoogleDrive = async (media) => {
fileName = saveMedia(media);
filePath = `${__dirname}/../media/${fileName}`
const googleDriveUrl = await uploadSingleFile(fileName, filePath);
return googleDriveUrl
}
module.exports = { saveMedia, saveMediaToGoogleDrive }

View File

@@ -1,115 +0,0 @@
const ExcelJS = require('exceljs');
const moment = require('moment');
const fs = require('fs');
const { MessageMedia, Buttons } = require('whatsapp-web.js');
const { cleanNumber } = require('./handle')
const DELAY_TIME = 170; //ms
const DIR_MEDIA = `${__dirname}/../mediaSend`;
// import { Low, JSONFile } from 'lowdb'
// import { join } from 'path'
const { saveMessage } = require('../adapter')
/**
* Enviamos archivos multimedia a nuestro cliente
* @param {*} number
* @param {*} fileName
*/
const sendMedia = (client, number = null, fileName = null) => {
if(!client) return console.error("El objeto cliente no está definido.");
try {
number = cleanNumber(number || 0)
const file = `${DIR_MEDIA}/${fileName}`;
if (fs.existsSync(file)) {
const media = MessageMedia.fromFilePath(file);
client.sendMessage(number, media, { sendAudioAsVoice: true });
}
} catch(e) {
throw e;
}
}
/**
* Enviamos archivos como notas de voz
* @param {*} number
* @param {*} fileName
*/
const sendMediaVoiceNote = (client, number = null, fileName = null) => {
if(!client) return console.error("El objeto cliente no está definido.");
try {
number = cleanNumber(number || 0)
const file = `${DIR_MEDIA}/${fileName}`;
if (fs.existsSync(file)) {
const media = MessageMedia.fromFilePath(file);
client.sendMessage(number, media ,{ sendAudioAsVoice: true });
}
}catch(e) {
throw e;
}
}
/**
* Enviamos un mensaje simple (texto) a nuestro cliente
* @param {*} number
*/
const sendMessage = async (client, number = null, text = null, trigger = null) => {
setTimeout(async () => {
number = cleanNumber(number)
const message = text
client.sendMessage(number, message);
await readChat(number, message, trigger)
console.log(`⚡⚡⚡ Enviando mensajes....`);
},DELAY_TIME)
}
/**
* Enviamos un mensaje con buttons a nuestro cliente
* @param {*} number
*/
const sendMessageButton = async (client, number = null, text = null, actionButtons) => {
setTimeout(async () => {
number = cleanNumber(number)
const { title = null, message = null, footer = null, buttons = [] } = actionButtons;
let button = new Buttons(message,[...buttons], title, footer);
client.sendMessage(number, button);
await readChat(number, message, actionButtons)
console.log(`⚡⚡⚡ Enviando mensajes....`);
}, DELAY_TIME)
}
/**
* Opte
*/
const lastTrigger = (number) => new Promise((resolve, reject) => {
number = cleanNumber(number)
const pathExcel = `${__dirname}/../chats/${number}.xlsx`;
const workbook = new ExcelJS.Workbook();
if (fs.existsSync(pathExcel)) {
workbook.xlsx.readFile(pathExcel)
.then(() => {
const worksheet = workbook.getWorksheet(1);
const lastRow = worksheet.lastRow;
const getRowPrevStep = worksheet.getRow(lastRow.number);
const lastStep = getRowPrevStep.getCell('C').value;
resolve(lastStep)
});
} else {
resolve(null)
}
})
/**
* Guardar historial de conversacion
* @param {*} number
* @param {*} message
*/
const readChat = async (number, message, trigger = null) => {
number = cleanNumber(number)
await saveMessage( message, trigger, number )
console.log('Saved')
}
module.exports = { sendMessage, sendMedia, lastTrigger, sendMessageButton, readChat, sendMediaVoiceNote }

View File

@@ -1,16 +0,0 @@
module.exports = (socket) => {
return {
sendQR:(qr) => {
socket.emit('connection_qr',{
qr
})
},
sendStatus:() => {
socket.emit('connection_status',{
a:1
})
}
}
}

View File

@@ -1,17 +0,0 @@
const fs = require('fs')
const { sendMessage } = require('../controllers/send')
const sendMessagePost = (req, res) => {
console.log('asdasdasdasdasd')
const { message, number } = req.body
const client = req.clientWs || null;
sendMessage(client, number, message)
res.send({ status: 'Enviado!' })
}
const getQr = (req, res) => {
res.writeHead(200, { 'content-type': 'image/svg+xml' });
fs.createReadStream(`${__dirname}/../mediaSend/qr-code.svg`).pipe(res);
}
module.exports = { sendMessagePost, getQr }

25
docker-compose.yml Normal file
View File

@@ -0,0 +1,25 @@
version: '3.3'
services:
mongo:
image: mongo
container_name: app_enviroment
restart: always
ports:
- '27019:27017'
environment:
MONGO_INITDB_DATABASE: bot
expose:
- 27019
mysql:
image: mysql
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: example
MYSQL_DATABASE: bot
container_name: app_mysql
ports:
- '3306:3306'
expose:
- 3306

View File

@@ -1,8 +0,0 @@
[
{
"phrases": [
"Se requiere una foto de alguna identificación por razones de seguridad.",
"Por favor envíenos una foto de su ID para completar su formulario."
]
}
]

View File

@@ -1,93 +0,0 @@
[
{
"keywords": [
"hola",
"hola!",
"ola",
"ole",
"inicio",
"welcome",
"buenos días",
"buenas tardes",
"buenas noches",
"me dieron este número",
"venden a crédito",
"quisiera saber si venden",
"necesito saber"
],
"key": "STEP_1"
},
{
"keywords": [
"cursos",
"info",
"curso" ],
"key": "STEP_2"
},
{
"keywords": [
"angular"
],
"key": "STEP_2_1"
},
{
"keywords": [
"node"
],
"key": "STEP_2_2"
},
{
"keywords": [
"ngrx"
],
"key": "STEP_2_3"
},
{
"keywords": [
"aws"
],
"key": "STEP_2_4"
},
{
"keywords": [
"asesor",
"asesores",
"Vendedor",
"cobrador"
],
"key": "STEP_3"
},
{
"keywords": [
"muchas gracias",
"ok",
"gracias",
"vale gracias"
],
"key": "STEP_4"
},
{
"keywords": [
"youtube"
],
"key": "STEP_5"
},
{
"keywords": [
"VER_CURSOS"
],
"key": "STEP_6"
},
{
"keywords": [
"telegram"
],
"key": "STEP_7"
},
{
"keywords": [
"audio"
],
"key": "STEP_8"
}
]

View File

@@ -1,148 +0,0 @@
{
"DEFAULT":{
"replyMessage":[
"*Esta respuesta es un respuesta default* cuando no se consigue una palabra clave \n",
"la puedes desactivar en tu archivo .env DEFAULT_MESSAGE=false \n",
"tambien te quiero recordar que si presentas algun error pasarte por el repositorio \n",
"https://github.com/leifermendez/bot-whatsapp#chatbot-whatsapp-opensource \n",
"y recuerda tener la ultima versión del proyecto \n\n",
"Prueba escribiendo *hola* \n"
],
"media":null,
"trigger":null
},
"STEP_0":{
"replyMessage":[
"El flujo ha finalizado \n",
"pero puedes ver todo el codigo de este \n",
"repositorio en https://github.com/leifermendez/bot-whatsapp.git"
],
"media":null,
"trigger":null
},
"STEP_1":{
"replyMessage":[
"Hola! y✌ Bienvenido a este 🤖 CHATBOT de Whatsapp, lo primero \n",
"decirte que mi nombre es *Leifer Mendez*😎 \n",
"\n Si necesitas ver más info sobre las capacitacion tecnicas ",
"escribe *cursos* o *info* o escribe *audio*"
],
"media":"https://media2.giphy.com/media/VQJu0IeULuAmCwf5SL/giphy.gif",
"trigger":null,
"actions":{
"title":"¿Que te interesa ver?",
"message":"Recuerda todo este contenido es gratis y estaria genial que me siguas!",
"footer":"Gracias",
"buttons":[
{"body":"Cursos"},
{"body":"Youtube"},
{"body":"Telegram"}
]
}
},
"STEP_2":{
"replyMessage":[
"Perfecto, te voy a pasar la lista ",
"de los temas que tengo y un breve video 🙂🤖 \n\n",
"*Angular* Basico (Pago) \n",
"*Angular* Basico (Gratis) \n",
"*Node* Basico (Gratis) \n",
"*NGRX* Basico (Gratis) \n",
"*AWS* Basico (Pago) \n\n",
"Escribe la palabra del tema que te interese \n"
],
"media":"https://i.giphy.com/media/5J5gN0WUk0VToHaK2p/giphy-downsized.gif",
"trigger":null
},
"STEP_2_1":{
"replyMessage":[
"Si te interesa Angular tienes disponible \n",
"*(Gratis)* https://bit.ly/367tJ32 \n\n",
"*(Pago)* https://link.codigoencasa.com/PROMO-INICIAL \n\n",
"*(Pago)* https://link.codigoencasa.com/ANGULAR-BASICO-EDTEAM \n\n",
"😎😎😎"
],
"media":"https://i.imgur.com/Q0a5UQI.jpg",
"trigger":null
},
"STEP_2_2":{
"replyMessage":[
"Si te interesa NODE tienes disponible \n",
"*(Gratis)* https://bit.ly/3od1Bl6 \n\n",
"Espero pronto tener más material disponible",
"🤖"
],
"media":null,
"trigger":null
},
"STEP_2_3":{
"replyMessage":[
"NGRX para manejar estados en Angular \n",
"*(Gratis)* https://bit.ly/ngrx-desde-cero \n",
"A darle! 😮"
],
"media":null,
"trigger":null
},
"STEP_2_4":{
"replyMessage":[
"Muy bien AWS esta pronto a salir pre-registrate aquí \n",
"*(Pre-registro)* https://link.codigoencasa.com/AWS-BASICO-INVITACION \n",
"😮😮"
],
"media":null,
"trigger":null
},
"STEP_3":{
"replyMessage":[
"¿Ok cual curso de intereso? \n",
"*angular* , *node*, *ngrx*, *aws*"
],
"media":null,
"trigger":null
},
"STEP_4":{
"replyMessage":[
"Gracias a ti! \n"
],
"media":"https://media4.giphy.com/media/hur0SFIU5SH4mxNBWa/giphy.gif",
"trigger":null
},
"STEP_5":{
"replyMessage":[
"Muy bien te comparto el canal de Youtube \n",
"https://youtube.com/leifermendez \n"
],
"media":null,
"trigger":null
},
"STEP_6":{
"replyMessage":[
"Perfecto, te voy a pasar la lista ",
"de los temas que tengo y un breve video 🙂🤖 \n\n",
"*Angular* Basico (Pago) \n",
"*Angular* Basico (Gratis) \n",
"*Node* Basico (Gratis) \n",
"*NGRX* Basico (Gratis) \n",
"*AWS* Basico (Pago) \n\n",
"Escribe la palabra del tema que te interese \n"
],
"media":"https://i.giphy.com/media/5J5gN0WUk0VToHaK2p/giphy-downsized.gif",
"trigger":null
},
"STEP_7":{
"replyMessage":[
"Vente al telegram \n",
"https://t.me/leifermendez \n"
],
"media":null,
"trigger":null
},
"STEP_8":{
"replyMessage":[
"Esto es una nota de voz \n"
],
"media":"nota-de-voz.mp3",
"trigger":null
}
}

Binary file not shown.

Binary file not shown.

View File

@@ -1,21 +0,0 @@
const middlewareClient = (client = null) => async (req, res, next) => {
try {
if(!client){
res.status(409)
console.log(client)
res.send({ error: 'Error de client.' })
}else{
req.clientWs = client;
next()
}
} catch (e) {
console.log(e)
res.status(409)
res.send({ error: 'Error de client' })
}
}
module.exports = { middlewareClient }

View File

9467
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,58 +1,97 @@
{
"name": "bot-whatsapp",
"version": "1.0.0",
"description": "Bot de wahtsapp open source para MVP o pequeños negocios",
"main": "app.js",
"scripts": {
"start": "node ./app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"whatsapp",
"bot-whatsapp",
"node-bot-whatsapp"
],
"contributors": [
{
"email": "leifer33@gmail.com",
"name": "Leifer Mendez",
"url": "https://leifermendez.github.io"
"name": "@bot-whatsapp/root",
"version": "0.1.3",
"description": "Bot de wahtsapp open source para MVP o pequeños negocios",
"main": "app.js",
"private": true,
"scripts": {
"commit": "git-cz",
"cli:rollup": "rollup --config ./packages/cli/rollup-cli.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",
"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 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",
"test": "npm run test.coverage",
"cli": "node ./packages/cli/bin/cli.js",
"create": "node ./packages/create-bot-whatsapp/bin/create.js",
"dev:debug": "node --inspect ./example-app/app.js",
"dev": "node ./example-app/app.js",
"prepare": "npx husky install",
"preinstall": "npx only-allow yarn",
"postinstall": "npx prettier --write .",
"release": "standard-version -- --prerelease"
},
{
"name": "aurik3",
"email": "aurik3@aurik3.com",
"url": "https://github.com/aurik3"
}
],
"repository": {
"type": "git",
"url": "https://github.com/leifermendez/bot-whatsapp"
},
"license": "ISC",
"dependencies": {
"@google-cloud/dialogflow": "^5.2.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"exceljs": "^4.3.0",
"express": "^4.18.1",
"file-type": "^17.1.6",
"googleapis": "^109.0.1",
"mime-db": "^1.52.0",
"moment": "^2.29.4",
"mysql": "^2.18.1",
"pb-util": "^1.0.3",
"qr-image": "^3.2.0",
"qrcode-terminal": "^0.12.0",
"socket.io": "^4.5.1",
"stormdb": "^0.6.0",
"whatsapp-web.js": "^1.18.4",
"xlsx": "^0.18.5"
},
"devDependencies": {
"pm2": "^5.2.0",
"prettier": "2.7.1"
},
"engines": {
"node": "16.x"
}
"workspaces": [
"packages/create-bot-whatsapp",
"packages/bot",
"packages/cli",
"packages/database",
"packages/provider",
"packages/contexts",
"packages/docs"
],
"keywords": [
"whatsapp",
"bot-whatsapp",
"node-bot-whatsapp"
],
"contributors": [
{
"email": "leifer33@gmail.com",
"name": "Leifer Mendez",
"url": "https://leifermendez.github.io"
},
{
"name": "aurik3",
"email": "aurik3@aurik3.com",
"url": "https://github.com/aurik3"
}
],
"repository": "https://github.com/leifermendez/bot-whatsapp",
"license": "ISC",
"devDependencies": {
"@commitlint/cli": "^17.3.0",
"@commitlint/config-conventional": "^17.3.0",
"@rollup/plugin-commonjs": "^23.0.2",
"@rollup/plugin-json": "^5.0.1",
"@rollup/plugin-node-resolve": "^15.0.1",
"@rollup/plugin-replace": "^5.0.1",
"c8": "^7.12.0",
"conventional-changelog": "^3.1.25",
"cross-env": "^7.0.3",
"eslint": "^8.26.0",
"eslint-config-prettier": "^8.5.0",
"fs-extra": "^11.1.0",
"git-cz": "^4.9.0",
"husky": "^8.0.2",
"only-allow": "^1.1.1",
"prettier": "^2.8.0",
"pretty-quick": "^3.1.3",
"prompts": "^2.4.2",
"rimraf": "^3.0.2",
"rollup": "^3.2.3",
"rollup-plugin-cleanup": "^3.2.1",
"rollup-plugin-copy": "^3.4.0",
"semver": "^7.3.8",
"standard-version": "^9.5.0",
"uvu": "^0.5.6"
},
"packageManager": "yarn@3.3.0",
"engines": {
"node": ">=16",
"npm": "please-use-yarn",
"yarn": ">=3"
},
"author": "Leifer Mendez <leifer33@gmail.com>"
}

110
packages/bot/USES_CASES.md Normal file
View File

@@ -0,0 +1,110 @@
# @bot-whatsapp/io
### Caso de uso
> Una persona escribe `hola`
**addKeyword** recibe `string | string[]`
> `sensitive` false _default_
- [x] addKeyword
- [x] addAnswer
- [x] addKeyword: Opciones
- [x] addAnswer: Opciones, media, buttons
- [x] Retornar JSON (options)
- [ ] Recibir JSON
```js
// bootstrap.js Como iniciar el provider
const { inout, provider, database } = require('@bot-whatsapp')
/**
* async whatsapp-web, twilio, meta
* */
const bootstrap = async () => {
console.log(`Iniciando....`)
const client = await provider.start()
/**
* - QR
* - Endpoint
* - Check Token Meta, Twilio
* - Return events? on message
* */
console.log(`Fin...`)
// Esto es opcional ? no deberia ser necesario
client.on('message', ({number, body,...}) => {
// Incoming message
})
}
```
```js
// flow.js Como agregar keywords y respuestas
const { inout, provider, database } = require('@bot-whatsapp')
await inout
.addKeyword('hola')
.addAnswer('Bienvenido a tu tienda 🥲')
.addAnswer('escribe *catalogo* o *ofertas*')
await inout
.addKeyword(['catalogo', 'ofertas'])
.addAnswer('Este es nuestro CATALOGO mas reciente!', {
buttons: [{ body: 'Xiaomi' }, { body: 'Samsung' }],
})
await inout
.addKeyword('Xiaomi')
.addAnswer('Estos son nuestro productos XIAOMI ....', {
media: 'https://....',
})
.addAnswer('Si quieres mas info escrbie *info*')
await inout
.addKeyword('chao!')
.addAnswer('bye!')
.addAnswer('Recuerda que tengo esta promo', {
media: 'https://media2.giphy.com/media/VQJu0IeULuAmCwf5SL/giphy.gif',
})
await inout
.addKeyword('Modelo C', { sensitive: false })
.addAnswer('100USD', { media: 'http//:...' })
await inout
.addKeyword('hola!', { sensitive: false })
.addAnswer('Bievenido Escribe *productos*')
await inout
.addKeyword('productos', { sensitive: false })
.addAnswer('Esto son los mas vendidos')
.addAnswer('*PC1* Precio 10USD', { media: 'https://....' })
.addAnswer('*PC2* Precio 10USD', { media: 'https://....' })
await inout
.addKeyword('PC1', { sensitive: false })
.addAnswer('Bievenido Escribe *productos*')
const answerOne = await inout.addAnswer({
message: 'Como estas!',
media: 'https://media2.giphy.com/media/VQJu0IeULuAmCwf5SL/giphy.gif',
})
const otherAnswer = await inout.addAnswer('Aprovecho para decirte!')
answerOne.push(otherAnswer)
inout.addKeywords(['hola', 'hi', 'ola'])
```
**Comunidad**
> Forma parte de este proyecto.
- [Discord](https://link.codigoencasa.com/DISCORD)
- [Twitter](https://twitter.com/leifermendez)
- [Youtube](https://www.youtube.com/watch?v=5lEMCeWEJ8o&list=PL_WGMLcL4jzWPhdhcUyhbFU6bC0oJd2BR)
- [Telegram](https://t.me/leifermendez)

View File

@@ -0,0 +1,204 @@
const { toCtx } = require('../io/methods')
const { printer } = require('../utils/interactive')
const { delay } = require('../utils/delay')
const Queue = require('../utils/queue')
const { Console } = require('console')
const { createWriteStream } = require('fs')
const logger = new Console({
stdout: createWriteStream(`${process.cwd()}/core.class.log`),
})
/**
* [ ] Escuchar eventos del provider asegurarte que los provider emitan eventos
* [ ] Guardar historial en db
* [ ] Buscar mensaje en flow
*
*/
class CoreClass {
flowClass
databaseClass
providerClass
constructor(_flow, _database, _provider) {
this.flowClass = _flow
this.databaseClass = _database
this.providerClass = _provider
for (const { event, func } of this.listenerBusEvents()) {
this.providerClass.on(event, func)
}
}
/**
* Manejador de eventos
*/
listenerBusEvents = () => [
{
event: 'preinit',
func: () => printer('Iniciando proveedor, espere...'),
},
{
event: 'require_action',
func: ({ instructions, title = '⚡⚡ ACCIÓN REQUERIDA ⚡⚡' }) =>
printer(instructions, title),
},
{
event: 'ready',
func: () => printer('Proveedor conectado y listo'),
},
{
event: 'auth_failure',
func: ({ instructions }) =>
printer(instructions, '⚡⚡ ERROR AUTH ⚡⚡'),
},
{
event: 'message',
func: (msg) => this.handleMsg(msg),
},
]
/**
* GLOSSARY.md
* @param {*} messageCtxInComming
* @returns
*/
handleMsg = async (messageCtxInComming) => {
logger.log(`[handleMsg]: `, messageCtxInComming)
const { body, from } = messageCtxInComming
let msgToSend = []
let fallBackFlag = false
if (!body.length) return
const prevMsg = await this.databaseClass.getPrevByNumber(from)
const refToContinue = this.flowClass.findBySerialize(
prevMsg?.refSerialize
)
if (prevMsg?.ref) {
const ctxByNumber = toCtx({
body,
from,
prevRef: prevMsg.refSerialize,
})
this.databaseClass.save(ctxByNumber)
}
// 📄 [options: fallBack]: esta funcion se encarga de repetir el ultimo mensaje
const fallBack = () => {
fallBackFlag = true
msgToSend = this.flowClass.find(refToContinue?.keyword, true) || []
this.sendFlow(msgToSend, from)
return refToContinue
}
// 📄 [options: flowDynamic]: esta funcion se encarga de responder un array de respuesta esta limitado a 5 mensajes
// para evitar bloque de whatsapp
const flowDynamic = (listMsg = [], optListMsg = { limit: 3 }) => {
if (!Array.isArray(listMsg))
throw new Error('Esto debe ser un ARRAY')
const parseListMsg = listMsg
.map(({ body }, index) =>
toCtx({
body,
from,
keyword: null,
index,
})
)
.slice(0, optListMsg.limit)
msgToSend = parseListMsg
this.sendFlow(msgToSend, from)
return
}
// 📄 Se encarga de revisar si el contexto del mensaje tiene callback y ejecutarlo
const cbEveryCtx = (inRef) => {
this.flowClass.allCallbacks[inRef](messageCtxInComming, {
fallBack,
flowDynamic,
})
}
// 📄 [options: callback]: Si se tiene un callback se ejecuta
if (!fallBackFlag) {
for (const ite of this.flowClass.find(body)) {
cbEveryCtx(ite?.ref)
}
}
// 📄🤘(tiene return) [options: nested(array)]: Si se tiene flujos hijos los implementa
if (!fallBackFlag && prevMsg?.options?.nested?.length) {
const nestedRef = prevMsg.options.nested
const flowStandalone = nestedRef.map((f) => ({
...nestedRef.find((r) => r.refSerialize === f.refSerialize),
}))
msgToSend = this.flowClass.find(body, false, flowStandalone) || []
for (const ite of msgToSend) {
cbEveryCtx(ite?.ref)
}
this.sendFlow(msgToSend, from)
return
}
// 📄🤘(tiene return) [options: capture (boolean)]: Si se tiene option boolean
if (!fallBackFlag && !prevMsg?.options?.nested?.length) {
const typeCapture = typeof prevMsg?.options?.capture
const valueCapture = prevMsg?.options?.capture
if (['string', 'boolean'].includes(typeCapture) && valueCapture) {
msgToSend = this.flowClass.find(refToContinue?.ref, true) || []
this.sendFlow(msgToSend, from)
return
}
}
msgToSend = this.flowClass.find(body) || []
this.sendFlow(msgToSend, from)
}
/**
* Enviar mensaje con contexto atraves del proveedor de whatsapp
* @param {*} numberOrId
* @param {*} ctxMessage ver más en GLOSSARY.md
* @returns
*/
sendProviderAndSave = (numberOrId, ctxMessage) => {
const { answer } = ctxMessage
return Promise.all([
this.providerClass.sendMessage(numberOrId, answer, ctxMessage),
this.databaseClass.save({ ...ctxMessage, from: numberOrId }),
])
}
sendFlow = async (messageToSend, numberOrId) => {
const queue = []
for (const ctxMessage of messageToSend) {
const delayMs = ctxMessage?.options?.delay || 0
if (delayMs) await delay(delayMs)
Queue.enqueue(() =>
this.sendProviderAndSave(numberOrId, ctxMessage)
)
}
return Promise.all(queue)
}
/**
* @private
* @param {*} message
* @param {*} ref
*/
continue = (message, ref = false) => {
const responde = this.flowClass.find(message, ref)
if (responde) {
this.providerClass.sendMessage(responde.answer)
this.databaseClass.saveLog(responde.answer)
this.continue(null, responde.ref)
}
}
}
module.exports = CoreClass

47
packages/bot/index.js Normal file
View File

@@ -0,0 +1,47 @@
const CoreClass = require('./core/core.class')
const ProviderClass = require('./provider/provider.class')
const FlowClass = require('./io/flow.class')
const { addKeyword, addAnswer, addChild, toSerialize } = require('./io/methods')
/**
* Crear instancia de clase Bot
* @param {*} args
* @returns
*/
const createBot = async ({ flow, database, provider }) =>
new CoreClass(flow, database, provider)
/**
* Crear instancia de clase Io (Flow)
* @param {*} args
* @returns
*/
const createFlow = (args) => {
return new FlowClass(args)
}
/**
* Crear instancia de clase Provider
* Depdendiendo del Provider puedes pasar argumentos
* Ver Documentacion
* @param {*} args
* @returns
*/
const createProvider = (providerClass = class {}, args = null) => {
const providerInstance = new providerClass(args)
if (!providerClass.prototype instanceof ProviderClass)
throw new Error('El provider no implementa ProviderClass')
return providerInstance
}
module.exports = {
createBot,
createFlow,
createProvider,
addKeyword,
addAnswer,
addChild,
toSerialize,
ProviderClass,
CoreClass,
}

View File

@@ -0,0 +1,65 @@
const { toSerialize } = require('./methods/toSerialize')
const { flatObject } = require('../utils/flattener')
class FlowClass {
allCallbacks = []
flowSerialize = []
flowRaw = []
constructor(_flow) {
if (!Array.isArray(_flow)) throw new Error('Esto debe ser un ARRAY')
this.flowRaw = _flow
this.allCallbacks = flatObject(_flow)
const mergeToJsonSerialize = Object.keys(_flow)
.map((indexObjectFlow) => _flow[indexObjectFlow].toJson())
.flat(2)
this.flowSerialize = toSerialize(mergeToJsonSerialize)
}
find = (keyOrWord, symbol = false, overFlow = null) => {
keyOrWord = `${keyOrWord}`
let capture = false
let messages = []
let refSymbol = null
overFlow = overFlow ?? this.flowSerialize
/** Retornar expresion regular para buscar coincidencia */
const mapSensitive = (str, flag = false) => {
const regexSensitive = flag ? 'g' : 'i'
if (Array.isArray(str)) {
return new RegExp(str.join('|'), regexSensitive)
}
return new RegExp(str, regexSensitive)
}
const findIn = (keyOrWord, symbol = false, flow = overFlow) => {
const sensitive = refSymbol?.options?.sensitive || false
capture = refSymbol?.options?.capture || false
if (capture) return messages
if (symbol) {
refSymbol = flow.find((c) => c.keyword === keyOrWord)
if (refSymbol?.answer) messages.push(refSymbol)
if (refSymbol?.ref) findIn(refSymbol.ref, true)
} else {
refSymbol = flow.find((c) => {
return mapSensitive(c.keyword, sensitive).test(keyOrWord)
})
if (refSymbol?.ref) findIn(refSymbol.ref, true)
return messages
}
}
findIn(keyOrWord, symbol)
return messages
}
findBySerialize = (refSerialize) =>
this.flowSerialize.find((r) => r.refSerialize === refSerialize)
findIndexByRef = (ref) => this.flowSerialize.findIndex((r) => r.ref === ref)
}
module.exports = FlowClass

View File

@@ -0,0 +1,111 @@
const { flatObject } = require('../../utils/flattener')
const { generateRef } = require('../../utils/hash')
const { addChild } = require('./addChild')
const { toJson } = require('./toJson')
/**
*
* @param answer string
* @param options {media:string, buttons:[{"body":"😎 Cursos"}], delay:ms, capture:true default false}
* @returns
*/
const addAnswer =
(inCtx) =>
(answer, options, cb = null, nested = []) => {
answer = Array.isArray(answer) ? answer.join('\n') : answer
/**
* Todas las opciones referentes a el mensaje en concreto options:{}
* @returns
*/
const getAnswerOptions = () => ({
media:
typeof options?.media === 'string' ? `${options?.media}` : null,
buttons: Array.isArray(options?.buttons) ? options.buttons : [],
capture:
typeof options?.capture === 'boolean'
? options?.capture
: false,
child:
typeof options?.child === 'string' ? `${options?.child}` : null,
delay: typeof options?.delay === 'number' ? options?.delay : 0,
})
const getNested = () => {
let flatNested = []
if (Array.isArray(nested)) {
for (const iterator of nested) {
flatNested = [...flatNested, ...addChild(iterator)]
}
return {
nested: flatNested,
}
}
return {
nested: addChild(nested),
}
}
/**
* Esta funcion aplana y busca los callback anidados de los hijos
* @returns
*/
const getCbFromNested = () =>
flatObject(Array.isArray(nested) ? nested : [nested])
const callback = typeof cb === 'function' ? cb : () => null
const lastCtx = inCtx.hasOwnProperty('ctx') ? inCtx.ctx : inCtx
/**
* Esta funcion se encarga de mapear y transformar todo antes
* de retornar
* @returns
*/
const ctxAnswer = () => {
const ref = `ans_${generateRef()}`
const options = {
...getAnswerOptions(),
...getNested(),
keyword: {},
callback: !!cb,
}
const json = [].concat(inCtx.json).concat([
{
ref,
keyword: lastCtx.ref,
answer,
options,
},
])
getCbFromNested()
const callbacks = {
...inCtx.callbacks,
...getCbFromNested(),
[ref]: callback,
}
return {
...lastCtx,
ref,
answer,
json,
options,
callbacks,
}
}
/// Retornar contexto no colocar nada más abajo de esto
const ctx = ctxAnswer()
return {
ctx,
ref: ctx.ref,
addAnswer: addAnswer(ctx),
toJson: toJson(ctx),
}
}
module.exports = { addAnswer }

View File

@@ -0,0 +1,15 @@
const { toSerialize } = require('./toSerialize')
/**
* @deprecate
* @param answer string
* @param options {media:string, buttons:[], capture:true default false}
* @returns
*/
const addChild = (flowIn = null) => {
if (!flowIn?.toJson) {
throw new Error('DEBE SER UN FLOW CON toJSON()')
}
return toSerialize(flowIn.toJson())
}
module.exports = { addChild }

View File

@@ -0,0 +1,49 @@
const { generateRef } = require('../../utils/hash')
const { addAnswer } = require('./addAnswer')
const { toJson } = require('./toJson')
/**
*
* @param {*} message `string | string[]`
* @param {*} options {sensitive:boolean} default false
*/
const addKeyword = (keyword, options) => {
const parseOptions = () => {
const defaultProperties = {
sensitive:
typeof options?.sensitive === 'boolean'
? options?.sensitive
: false,
}
return defaultProperties
}
const ctxAddKeyword = () => {
const ref = `key_${generateRef()}`
const options = parseOptions()
const json = [
{
ref,
keyword,
options,
},
]
/**
* Se guarda en db
*/
return { ref, keyword, options, json }
}
const ctx = ctxAddKeyword()
return {
ctx,
ref: ctx.ref,
addAnswer: addAnswer(ctx),
toJson: toJson(ctx),
}
}
module.exports = { addKeyword }

View File

@@ -0,0 +1,8 @@
const { addAnswer } = require('./addAnswer')
const { addKeyword } = require('./addKeyword')
const { addChild } = require('./addChild')
const { toSerialize } = require('./toSerialize')
const { toCtx } = require('./toCtx')
const { toJson } = require('./toJson')
module.exports = { addAnswer, addKeyword, addChild, toCtx, toJson, toSerialize }

View File

@@ -0,0 +1,19 @@
const { generateRef, generateRefSerialize } = require('../../utils/hash')
/**
* @deprecate
* @param answer string
* @param options {media:string, buttons:[], capture:true default false}
* @returns
*/
const toCtx = ({ body, from, prevRef, index }) => {
return {
ref: generateRef(),
keyword: prevRef,
answer: body,
options: {},
from,
refSerialize: generateRefSerialize({ index, answer: body }),
}
}
module.exports = { toCtx }

View File

@@ -0,0 +1,6 @@
const toJson = (inCtx) => () => {
const lastCtx = inCtx.hasOwnProperty('ctx') ? inCtx.ctx : inCtx
return lastCtx.json
}
module.exports = { toJson }

View File

@@ -0,0 +1,23 @@
const { generateRefSerialize } = require('../../utils/hash')
/**
* Crear referencia serializada
* @param {*} flowJson
* @returns array[]
*/
const toSerialize = (flowJson) => {
if (!Array.isArray(flowJson)) throw new Error('Esto debe ser un ARRAY')
const jsonToSerialize = flowJson.map((row, index) => ({
...row,
refSerialize: `${generateRefSerialize({
index,
keyword: row.keyword,
answer: row.answer,
})}`,
}))
return jsonToSerialize
}
module.exports = { toSerialize }

View File

@@ -0,0 +1,14 @@
const commonjs = require('@rollup/plugin-commonjs')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const { join } = require('path')
const PATH = join(__dirname, 'lib', 'io', 'bundle.io.cjs')
module.exports = {
input: 'index.js',
output: {
file: PATH,
format: 'cjs',
},
plugins: [commonjs(), nodeResolve()],
}

32
packages/bot/package.json Normal file
View File

@@ -0,0 +1,32 @@
{
"name": "@bot-whatsapp/bot",
"version": "0.0.38-alpha.0",
"description": "",
"main": "./lib/bundle.bot.cjs",
"scripts": {
"bot:rollup": "node ../../node_modules/.bin/rollup index.js --config ./rollup-cli.config.js",
"format:check": "prettier --check .",
"format:write": "prettier --write .",
"lint:check": "eslint .",
"lint:fix": "eslint --fix .",
"test.unit": "cross-env NODE_ENV=test node ../../node_modules/uvu/bin.js tests"
},
"keywords": [],
"files": [
"./lib/bundle.bot.cjs",
"./provider/*",
"./core/*",
"./io/*"
],
"author": "",
"license": "ISC",
"devDependencies": {
"@bot-whatsapp/cli": "*",
"@bot-whatsapp/database": "*",
"@bot-whatsapp/provider": "*",
"kleur": "^4.1.5"
},
"dependencies": {
"dotenv": "^16.0.3"
}
}

View File

@@ -0,0 +1,29 @@
const { EventEmitter } = require('node:events')
/**
* Esta clase debe siempre proporcionar los siguietes metodos
* sendMessage = Para enviar un mensaje
*
* @important
* Esta clase extiende de la clase del provider OJO
* Eventos
* - message
* - ready
* - error
* - require_action
*/
const NODE_ENV = process.env.NODE_ENV || 'dev'
class ProviderClass extends EventEmitter {
/**
* events: message | auth | auth_error | ...
*
*/
sendMessage = async (userId, message) => {
if (NODE_ENV !== 'production')
console.log('[sendMessage]', { userId, message })
return message
}
}
module.exports = ProviderClass

View File

@@ -0,0 +1,25 @@
const banner = require('../../config/banner.rollup.json')
const commonjs = require('@rollup/plugin-commonjs')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const { join } = require('path')
module.exports = [
{
input: join(__dirname, 'index.js'),
output: {
banner: banner['banner.output'].join(''),
file: join(__dirname, 'lib', 'bundle.bot.cjs'),
format: 'cjs',
},
plugins: [commonjs(), nodeResolve()],
},
{
input: join(__dirname, 'index.js'),
output: {
banner: banner['banner.output'].join(''),
file: join(__dirname, 'lib', 'bundle.bot.cjs'),
format: 'cjs',
},
plugins: [commonjs(), nodeResolve()],
},
]

View File

@@ -0,0 +1,279 @@
const { test } = require('uvu')
const assert = require('uvu/assert')
const FlowClass = require('../io/flow.class')
const MockProvider = require('../../../__mocks__/mock.provider')
const {
createBot,
CoreClass,
createFlow,
createProvider,
ProviderClass,
} = require('../index')
class MockFlow {
allCallbacks = { ref: () => 1 }
flowSerialize = []
flowRaw = []
find = (arg) => {
if (arg) {
return [{ answer: 'answer', ref: 'ref' }]
} else {
return null
}
}
findBySerialize = () => ({})
findIndexByRef = () => 0
}
class MockDBA {
listHistory = []
save = () => {}
getPrevByNumber = () => {}
}
class MockDBB {
listHistory = []
save = () => {}
getPrevByNumber = () => ({
refSerialize: 'xxxxx',
ref: 'xxxx',
options: { callback: true },
})
}
class MockDBC {
listHistory = []
save = () => {}
getPrevByNumber = () => ({
refSerialize: 'xxxxx',
ref: 'xxxx',
options: { callback: true, nested: ['1', '2'] },
})
saveLog = () => {}
}
test(`[CoreClass] Probando instanciamiento de clase`, async () => {
const setting = {
flow: new MockFlow(),
database: new MockDBA(),
provider: new MockProvider(),
}
const bot = await createBot(setting)
assert.is(bot instanceof CoreClass, true)
})
test(`[CoreClass createFlow] Probando instanciamiento de clase`, async () => {
const mockCreateFlow = createFlow([])
assert.is(mockCreateFlow instanceof FlowClass, true)
})
test(`[CoreClass createProvider] Probando instanciamiento de clase`, async () => {
const mockCreateProvider = createProvider(MockProvider)
assert.is(mockCreateProvider instanceof ProviderClass, true)
})
test(`[Bot] Eventos 'require_action,ready,auth_failure,message '`, async () => {
let responseEvents = {}
const MOCK_EVENTS = {
require_action: {
instructions: 'Debes...',
},
ready: true,
auth_failure: {
instructions: 'Error...',
},
message: {
from: 'XXXXXX',
body: 'hola',
hasMedia: false,
},
}
const mockProvider = new MockProvider()
const setting = {
flow: new MockFlow(),
database: new MockDBA(),
provider: mockProvider,
}
await createBot(setting)
/// Escuchamos eventos
mockProvider.on(
'require_action',
(r) => (responseEvents['require_action'] = r)
)
mockProvider.on('ready', (r) => (responseEvents['ready'] = r))
mockProvider.on('auth_failure', (r) => (responseEvents['auth_failure'] = r))
mockProvider.on('message', (r) => (responseEvents['message'] = r))
/// Emitimos eventos
mockProvider.delaySendMessage(
0,
'require_action',
MOCK_EVENTS.require_action
)
mockProvider.delaySendMessage(0, 'ready', MOCK_EVENTS.ready)
mockProvider.delaySendMessage(0, 'auth_failure', MOCK_EVENTS.auth_failure)
mockProvider.delaySendMessage(0, 'message', MOCK_EVENTS.message)
await delay(0)
/// Testeamos eventos
assert.is(
JSON.stringify(responseEvents.require_action),
JSON.stringify(MOCK_EVENTS.require_action)
)
assert.is(responseEvents.ready, MOCK_EVENTS.ready)
assert.is(
JSON.stringify(responseEvents.auth_failure),
JSON.stringify(MOCK_EVENTS.auth_failure)
)
assert.is(
JSON.stringify(responseEvents.message),
JSON.stringify(MOCK_EVENTS.message)
)
})
test(`[Bot] Probando Flujos Internos`, async () => {
let responseEvents = {}
const MOCK_EVENTS = {
require_action: {
instructions: 'Debes...',
},
ready: true,
auth_failure: {
instructions: 'Error...',
},
message: {
from: 'XXXXXX',
body: 'hola',
hasMedia: false,
},
}
const mockProvider = new MockProvider()
const setting = {
flow: new MockFlow(),
database: new MockDBB(),
provider: mockProvider,
}
await createBot(setting)
/// Escuchamos eventos
mockProvider.on(
'require_action',
(r) => (responseEvents['require_action'] = r)
)
mockProvider.on('ready', (r) => (responseEvents['ready'] = r))
mockProvider.on('auth_failure', (r) => (responseEvents['auth_failure'] = r))
mockProvider.on('message', (r) => (responseEvents['message'] = r))
/// Emitimos eventos
mockProvider.delaySendMessage(
0,
'require_action',
MOCK_EVENTS.require_action
)
mockProvider.delaySendMessage(0, 'ready', MOCK_EVENTS.ready)
mockProvider.delaySendMessage(0, 'auth_failure', MOCK_EVENTS.auth_failure)
mockProvider.delaySendMessage(0, 'message', MOCK_EVENTS.message)
await delay(0)
/// Testeamos eventos
assert.is(
JSON.stringify(responseEvents.require_action),
JSON.stringify(MOCK_EVENTS.require_action)
)
assert.is(responseEvents.ready, MOCK_EVENTS.ready)
assert.is(
JSON.stringify(responseEvents.auth_failure),
JSON.stringify(MOCK_EVENTS.auth_failure)
)
assert.is(
JSON.stringify(responseEvents.message),
JSON.stringify(MOCK_EVENTS.message)
)
})
test(`[Bot] Probando Flujos Nested`, async () => {
let responseEvents = {}
const MOCK_EVENTS = {
require_action: {
instructions: 'Debes...',
},
ready: true,
auth_failure: {
instructions: 'Error...',
},
message: {
from: 'XXXXXX',
body: 'hola',
hasMedia: false,
},
}
const mockProvider = new MockProvider()
const setting = {
flow: new MockFlow(),
database: new MockDBC(),
provider: mockProvider,
}
const botInstance = await createBot(setting)
botInstance.sendProviderAndSave('xxxxx', 'xxxxx')
botInstance.continue('xxxxx', 'xxxxx')
/// Escuchamos eventos
mockProvider.on(
'require_action',
(r) => (responseEvents['require_action'] = r)
)
mockProvider.on('ready', (r) => (responseEvents['ready'] = r))
mockProvider.on('auth_failure', (r) => (responseEvents['auth_failure'] = r))
mockProvider.on('message', (r) => (responseEvents['message'] = r))
/// Emitimos eventos
mockProvider.delaySendMessage(
0,
'require_action',
MOCK_EVENTS.require_action
)
mockProvider.delaySendMessage(0, 'ready', MOCK_EVENTS.ready)
mockProvider.delaySendMessage(0, 'auth_failure', MOCK_EVENTS.auth_failure)
mockProvider.delaySendMessage(0, 'message', MOCK_EVENTS.message)
await delay(0)
/// Testeamos eventos
assert.is(
JSON.stringify(responseEvents.require_action),
JSON.stringify(MOCK_EVENTS.require_action)
)
assert.is(responseEvents.ready, MOCK_EVENTS.ready)
assert.is(
JSON.stringify(responseEvents.auth_failure),
JSON.stringify(MOCK_EVENTS.auth_failure)
)
assert.is(
JSON.stringify(responseEvents.message),
JSON.stringify(MOCK_EVENTS.message)
)
})
test.run()
function delay(ms) {
return new Promise((res) => setTimeout(res, ms))
}

View File

@@ -0,0 +1,161 @@
const { test } = require('uvu')
const assert = require('uvu/assert')
const { generateRefSerialize } = require('../utils/hash')
const { addKeyword, addAnswer, toSerialize } = require('../io/methods')
test('Debere probar las propeidades', () => {
const ARRANGE = {
keyword: 'hola!',
}
const MAIN_CTX = addKeyword(ARRANGE.keyword)
assert.type(MAIN_CTX.addAnswer, 'function')
assert.is(MAIN_CTX.ctx.keyword, ARRANGE.keyword)
})
test('Debere probar las propeidades array', () => {
const ARRANGE = {
keyword: ['hola!', 'ole'],
}
const MAIN_CTX = addKeyword(ARRANGE.keyword)
assert.is(MAIN_CTX.ctx.keyword, ARRANGE.keyword)
})
test('Debere probar las propeidades array en answer', () => {
const ARRANGE = {
keyword: ['hola!', 'ole'],
}
const MAIN_CTX = addKeyword(ARRANGE.keyword).addAnswer(['hola', 'chao'])
assert.is(MAIN_CTX.ctx.keyword, ARRANGE.keyword)
})
test('Debere probar toSerialize', () => {
const ARRANGE = {
keyword: ['hola!', 'ole'],
}
const MAIN_CTX = addKeyword(ARRANGE.keyword)
.addAnswer('Segundo!')
.addAnswer('Segundo!')
.toJson()
const [ANSWER_A] = MAIN_CTX
assert.is(
toSerialize(MAIN_CTX)[0].refSerialize,
generateRefSerialize({
index: 0,
answer: ANSWER_A.answer,
keyword: ANSWER_A.keyword,
})
)
})
test('Debere probar el paso de contexto', () => {
const ARRANGE = {
keyword: 'hola!',
answer: 'Bienvenido',
}
const CTX_A = addKeyword(ARRANGE.keyword)
const CTX_B = addAnswer(CTX_A)(ARRANGE.answer)
assert.is(CTX_A.ctx.keyword, ARRANGE.keyword)
assert.is(CTX_B.ctx.keyword, ARRANGE.keyword)
assert.is(CTX_B.ctx.answer, ARRANGE.answer)
})
test('Debere probar la anidación', () => {
const ARRANGE = {
keyword: 'hola!',
answer_A: 'Bienvenido',
answer_B: 'Continuar',
}
const MAIN_CTX = addKeyword(ARRANGE.keyword)
.addAnswer(ARRANGE.answer_A)
.addAnswer(ARRANGE.answer_B)
assert.is(MAIN_CTX.ctx.answer, ARRANGE.answer_B)
})
test('Debere probar las poptions', () => {
const MAIN_CTX = addKeyword('etc', { sensitive: false })
assert.is(MAIN_CTX.ctx.options.sensitive, false)
})
test('Debere probar las addAnswer', () => {
const MOCK_OPT = {
media: 'http://image.mock/mock.png',
buttons: [1],
}
const MAIN_CTX = addKeyword('hola').addAnswer('etc', MOCK_OPT)
assert.is(MAIN_CTX.ctx.options.media, MOCK_OPT.media)
assert.is(MAIN_CTX.ctx.options.buttons.length, 1)
})
test('Debere probar error las addAnswer', () => {
const MOCK_OPT = {
media: { a: 1, b: [] },
buttons: 'test',
}
const MAIN_CTX = addKeyword('hola').addAnswer('etc', MOCK_OPT)
assert.is(MAIN_CTX.ctx.options.media, null)
assert.is(MAIN_CTX.ctx.options.buttons.length, 0)
})
test('Obtener toJson', () => {
const [ctxA, ctxB, ctxC] = addKeyword('hola')
.addAnswer('pera!')
.addAnswer('chao')
.toJson()
assert.is(ctxA.keyword, 'hola')
assert.match(ctxA.ref, /^key_/)
assert.is(ctxB.answer, 'pera!')
assert.match(ctxB.ref, /^ans_/)
assert.is(ctxC.answer, 'chao')
assert.match(ctxC.ref, /^ans_/)
})
test('addKeyword toJson con sensitive', () => {
const [ctxA] = addKeyword('hola').toJson()
assert.is(ctxA.options.sensitive, false)
const [ctxB] = addKeyword('hola', { sensitive: true }).toJson()
assert.is(ctxB.options.sensitive, true)
})
test('addAnswer toJson con IMG', () => {
const [, ctxB, ctxC] = addKeyword('hola')
.addAnswer('bye!', {
media: 'http://mock.img/file-a.png',
})
.addAnswer('otro!', {
media: 'http://mock.img/file-b.png',
})
.toJson()
assert.is(ctxB.options.media, 'http://mock.img/file-a.png')
assert.is(ctxC.options.media, 'http://mock.img/file-b.png')
})
test('addAnswer toJson con BUTTONS', () => {
const [, ctxB] = addKeyword('hola')
.addAnswer('mis opciones!', {
buttons: [{ body: 'BTN_1' }, { body: 'BTN_2' }],
})
.toJson()
assert.is(ctxB.options.buttons.length, 2)
const [btnA, btnB] = ctxB.options.buttons
assert.is(btnA.body, 'BTN_1')
assert.is(btnB.body, 'BTN_2')
})
test.run()

View File

@@ -0,0 +1,4 @@
const delay = (miliseconds) =>
new Promise((res) => setTimeout(res, miliseconds))
module.exports = { delay }

View File

@@ -0,0 +1,25 @@
const flatObject = (listArray = []) => {
const cbNestedList = Array.isArray(listArray) ? listArray : []
if (!listArray.length) return {}
const cbNestedObj = cbNestedList
.map(({ ctx }) => ctx?.callbacks)
.filter((i) => !!i)
const queueCb = cbNestedObj.reduce((acc, current) => {
const getKeys = Object.keys(current)
const parse = getKeys.map((icb, i) => ({
[icb]: Object.values(current)[i],
}))
return [...acc, ...parse]
}, [])
const flatObj = {}
for (const iteration of queueCb) {
const [keyCb] = Object.keys(iteration)
flatObj[keyCb] = iteration[keyCb]
}
return flatObj
}
module.exports = { flatObject }

View File

@@ -0,0 +1,24 @@
const crypto = require('crypto')
/**
* Generamos un UUID unico con posibilidad de tener un prefijo
* @param {*} prefix
* @returns
*/
const generateRef = (prefix = false) => {
const id = crypto.randomUUID()
return prefix ? `${prefix}_${id}` : id
}
/**
* Genera un HASH MD5
* @param {*} param0
* @returns
*/
const generateRefSerialize = ({ index, answer, keyword }) =>
crypto
.createHash('md5')
.update(JSON.stringify({ index, answer, keyword }))
.digest('hex')
module.exports = { generateRef, generateRefSerialize }

View File

@@ -0,0 +1,14 @@
const { yellow, bgRed } = require('kleur')
const NODE_ENV = process.env.NODE_ENV || 'dev'
const printer = (message, title) => {
if (NODE_ENV !== 'test') {
// console.clear()
if (title) console.log(bgRed(`${title}`))
console.log(
yellow(Array.isArray(message) ? message.join('\n') : message)
)
console.log(``)
}
}
module.exports = { printer }

View File

@@ -0,0 +1,46 @@
class Queue {
static queue = []
static pendingPromise = false
static enqueue(promise) {
return new Promise((resolve, reject) => {
this.queue.push({
promise,
resolve,
reject,
})
this.dequeue()
})
}
static dequeue() {
if (this.workingOnPromise) {
return false
}
const item = this.queue.shift()
if (!item) {
return false
}
try {
this.workingOnPromise = true
item.promise()
.then((value) => {
this.workingOnPromise = false
item.resolve(value)
this.dequeue()
})
.catch((err) => {
this.workingOnPromise = false
item.reject(err)
this.dequeue()
})
} catch (err) {
this.workingOnPromise = false
item.reject(err)
this.dequeue()
}
return true
}
}
module.exports = Queue

20
packages/cli/README.md Normal file
View File

@@ -0,0 +1,20 @@
# @bot-whatsapp/cli
- [x] Revisar version de NODE
- [x] Revisar OS
- [x] Obtener Package Manager
- [x] Revisar las libreria de WhatsappWeb para obtener version reciente
- [x] Opcion interactiva de limpiar session
- [x] Opcion de generar `json` con la configuracion
- [x] Agregar `rollup` para limpiar el codigo
---
**Comunidad**
> Forma parte de este proyecto.
- [Discord](https://link.codigoencasa.com/DISCORD)
- [Twitter](https://twitter.com/leifermendez)
- [Youtube](https://www.youtube.com/watch?v=5lEMCeWEJ8o&list=PL_WGMLcL4jzWPhdhcUyhbFU6bC0oJd2BR)
- [Telegram](https://t.me/leifermendez)

3
packages/cli/bin/cli.js Executable file
View File

@@ -0,0 +1,3 @@
#!/usr/bin/env node
const index = require('../lib/cli/bundle.cli.cjs')
index.startInteractive()

View File

@@ -0,0 +1,38 @@
const { red, yellow, green, bgCyan } = require('kleur')
const checkNodeVersion = () => {
console.log(bgCyan('🚀 Revisando tu Node.js'))
const version = process.version
const majorVersion = parseInt(version.replace('v', '').split('.').shift())
if (majorVersion < 16) {
console.error(
red(
`🔴 Se require Node.js 16 o superior. Actualmente esta ejecutando Node.js ${version}`
)
)
process.exit(1)
}
console.log(green(`Node.js compatible ${version}`))
console.log(``)
}
const checkOs = () => {
console.log(bgCyan('🙂 Revisando tu sistema operativo'))
const os = process.platform
if (!os.includes('win32')) {
const messages = [
`El sistema operativo actual (${os}) posiblemente requiera`,
`una configuración adicional referente al puppeteer`,
``,
`Recuerda pasar por el WIKI`,
`🔗 https://github.com/leifermendez/bot-whatsapp/wiki/Instalación`,
``,
]
console.log(yellow(messages.join(' \n')))
}
console.log(``)
}
module.exports = { checkNodeVersion, checkOs }

View File

@@ -0,0 +1,19 @@
const rimraf = require('rimraf')
const { yellow } = require('kleur')
const { join } = require('path')
const PATH_WW = [
join(process.cwd(), '.wwebjs_auth'),
join(process.cwd(), 'session.json'),
]
const cleanSession = () => {
const queue = []
for (const PATH of PATH_WW) {
console.log(yellow(`😬 Eliminando: ${PATH}`))
queue.push(rimraf(PATH, () => Promise.resolve()))
}
return Promise.all(queue)
}
module.exports = { cleanSession }

View File

@@ -0,0 +1,33 @@
const { writeFile } = require('fs').promises
const { join } = require('path')
/**
* JSON_TEMPLATE = {[key:string]{...pros}}
*/
const JSON_TEMPLATE = {
provider: {
vendor: '',
},
database: {
host: '',
password: '',
port: '',
username: '',
db: '',
},
io: {
vendor: '',
},
}
const PATH_CONFIG = join(process.cwd(), 'config.json')
const jsonConfig = () => {
return writeFile(
PATH_CONFIG,
JSON.stringify(JSON_TEMPLATE, null, 2),
'utf-8'
)
}
module.exports = { jsonConfig }

View File

@@ -0,0 +1,25 @@
const fs = require('fs-extra')
/**
* Copy files
*/
const copyFiles = async (from, to) => {
try {
await fs.copy(from, to)
console.log('success!')
} catch (err) {
console.error(err)
}
}
/**
* Copiar directorio con archivos
* @param {*} templateName
*/
const copyBaseApp = async (fromDir = process.cwd(), toDir = process.cwd()) => {
const BASEP_APP_PATH_FROM = `${fromDir}`
const BASEP_APP_PATH_TO = `${toDir}`
await copyFiles(BASEP_APP_PATH_FROM, BASEP_APP_PATH_TO)
}
module.exports = { copyBaseApp }

3
packages/cli/index.js Normal file
View File

@@ -0,0 +1,3 @@
const { startInteractive } = require('./interactive')
if (process.env.NODE_ENV === 'dev') startInteractive()
module.exports = { startInteractive }

View File

@@ -0,0 +1,24 @@
const { readFileSync, existsSync } = require('fs')
const { join } = require('path')
const { installDeps, getPkgManage } = require('./tool')
const PATHS_DIR = [
join(__dirname, 'pkg-to-update.json'),
join(__dirname, '..', 'pkg-to-update.json'),
join(__dirname, '..', '..', 'pkg-to-update.json'),
]
const PKG_TO_UPDATE = () => {
const PATH_INDEX = PATHS_DIR.findIndex((a) => existsSync(a))
const data = readFileSync(PATHS_DIR[PATH_INDEX], 'utf-8')
const dataParse = JSON.parse(data)
const pkg = Object.keys(dataParse).map((n) => `${n}@${dataParse[n]}`)
return pkg
}
const installAll = async () => {
const pkg = await getPkgManage()
installDeps(pkg, PKG_TO_UPDATE()).runInstall()
}
module.exports = { installAll }

Some files were not shown because too many files have changed in this diff Show More