Configuración inicial

1

Desarrolla tu Chatbot con la API de Whatsapp

2

¿Cómo funciona la API de WhatsApp?

3

¿Cómo crear una cuenta de desarrollador en Meta?

4

¿Cómo configurar una aplicación en Developers Facebook?

5

Creación y configuración de una aplicación en Whatsapp

Integración con la API de WhatsApp

6

¿Cómo configurar la API de WhatsApp para recibir y enviar mensajes?

7

¿Cómo configurar la API de WhatsaApp con Postman?

8

¿Cómo crear un servidor de Express?

Implementación de Servidor Express

9

¿Cómo implementar Webhooks en Express?

10

¿Cómo optimizar la arquitectura de un bot usando servicios y controladores?

Comunicación con la API de WhatsApp

11

¿Cómo enviar un mensaje de bienvenida con la API de WhatsApp?

12

¿Cómo configurar una respuesta personalizada desde la API de WhatsApp?

Flujos de Interacción con la API de WhatsApp

13

¿Cómo desarrollar un flujo inicial para guiar a los usuarios con WhatsApp API?

14

¿Cómo configurar un menú de opciones desde la API de WhatsApp?

Multimedia con WhatsApp API

15

¿Cómo integrar mensajes multimedia en el flujo de tu chatbot?

16

¿Cómo Integrar el Send-Media-Message al flujo de tu Chatbot?

17

¿Cómo crear el flujo para agendar una cita desde la API de WhatsApp?

18

¿Cómo crear una lógica que permita almacenar el flujo de tu Chatbot?

Avances y Personalización

19

¿Cómo conectar tu chatbot con Google Sheets para la gestión de datos?

20

¿Cómo configurar la API de Google Sheets para almacenar la información de tu usuario?

21

¿Cómo conectar la API de WhatsApp con ChatGPT?

22

¿Cómo integrar ChatGPT al flujo de la API de WhatsApp?

23

¿Cómo enviar contactos desde tu chatbot para soporte al usuario?

24

¿Cómo configurar la API de WhatsApp para enviar ubicaciones a tu usuario?

25

¿Cómo crear flujos escalables en la API de WhatsApp usando buenas prácticas de programación?

26

¿Cómo desplegar la API de WhatsApp en un ambiente de producción?

27

¿Cómo publicar tu Chatbot para interacciones reales?

28

Ahora tienes tu Chatbot que potencia las interacciones con tu usuario

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
4 Hrs
55 Min
40 Seg

¿Cómo optimizar la arquitectura de un bot usando servicios y controladores?

10/28
Resources

Implementing a scalable bot using an organized architecture is essential to manage its growth and adaptability to new services. In this approach, the Model-View-Controller (MVC) architecture is applied, dividing the project into specific components to ensure clarity and facilitate smooth future enhancements.

Why is it important to divide the code into modules?

Keeping all the logic in a single file might work for small projects, but as an application grows, it becomes unsustainable. Splitting the code allows:

  • Scalability: it makes it easy to add functions without affecting the stability of the system.
  • Maintainability: Isolating each function allows identifying and fixing bugs faster.
  • Collaboration: Allows multiple developers to work in different areas without interfering with each other.

How is the bot structure organized?

The project structure is divided into specific folders, located in a main folder called src, each one fulfilling a particular function:

  • config: Centralizes the configuration of environment variables so that they can be reused throughout the application without duplication.
  • controllers: In charge of receiving and handling incoming and outgoing requests. Here is located the webhook controller, responsible for managing Meta messages and Webhub routes.
  • routes: Defines the specific routes that the application will serve using Express.
  • services: Contains essential services, such as Message Handle and WhatsApp Service, which manage and send messages to the WhatsApp API.

What role do webhooks play in this configuration?

The webhooks, configured in the webhub controller file, handle POST and GET requests on the specified paths(/webhub). This controller allows:

  • Validate that the server is correctly connected to Meta.
  • Filter incoming messages according to their type and decide the corresponding actions (e.g., replicate or mark as read).

What does the WhatsApp Service class provide?

The WhatsApp Service class manages message sending and direct interaction with the WhatsApp API, which allows:

  • Send automatic replies depending on the type of message received.
  • Mark messages as read after replying, improving the user experience.

How does this architecture contribute to teamwork?

Modularization allows developers to work on specific components without interfering with others. This structure optimizes performance, avoids errors due to simultaneous code changes and ensures that future developments are implemented efficiently.

How is application initialization handled?

The App.js file centralizes the general configuration of the application, including:

  • Setting environment variables and Webhub paths.
  • Initialization of the server, leaving the request handling logic to the controllers and services.

Contributions 10

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Puedes clonar el proyecto desde este link: <https://github.com/platzi/whatsapp-api/commit/4e0d59e32c564a7afc8ab04ec777953ad479247b>
Hice lo mismo pero python ocupando Fast-api, por si alguien le interesa. [DarkCodePE/whatsapp-webhook-fast-api: This is a fast-api integration with whatsapp webhook.](https://github.com/DarkCodePE/whatsapp-webhook-fast-api/tree/master)
Alguien me puede ayudar con este error. Despues de crear los archivos del MVC, al ejecutar el comando npm run start, me abre el archivo de nodemon.js y no se ejecuta el programa ![](https://static.platzi.com/media/user_upload/image-fd35ce66-6ddd-40db-b720-c1a99d9ff7ce.jpg)
Note dos pequeños errores que me hicieron jugar un buen rato con el código, les paso los tips: 1.- el código que se muestra puede que no compile ...nodemon la extensión correcta .json para mi caso y funciono 2.-el mensaje genera error 400 y no se hace el echo... quite el contexto " context: {  message\_Id: messageId,                     }, " que estaba dentro del data con estos cambios ya se responde con la nueva estructura, me quedo pendiente el marcar el mensaje como leído, pero eso se vera en próximas clases.. espero, saludos. que
Algo no funciona, no está escuchando el puerto 3000, ayuda por favor
Lo repliqué a .Net!!
me tome el trabajo de ver 2 veces este clase.. linea por linea.. incluso comparando archivos de los recursos y no logro hacer que el boot, me responda.. me marca el msg enviado pero no me hace el reply!.-- El error lo tengo en la clase WhastsAppService, en el sendMesage **Error sending message: {"message":"Request failed with status code 400","name":"AxiosError","stack":"AxiosError: Request failed with status code 400\n at settle (file:///home/marcelo/code/WhatsApp%20API/medPets/medpetsboot/node\_modules/axios/lib/core/settle.js:19:12)\\**
```js import axios from 'axios'; import config from '../config/env.js'; class WhatsAppService { async sendMessage({ to , type, content }) { try { await axios({ method: 'POST', url: `https://graph.facebook.com/${config.API_VERSION}/${config.BUSINESS_PHONE}/messages`, headers: { Authorization: `Bearer ${config.API_TOKEN}`, }, data: { messaging_product: 'whatsapp', to, type, ...content }, }); } catch (error) { console.error('Error sending message:', error); } } async markAsRead(messageId) { try { await axios({ method: 'POST', url: `https://graph.facebook.com/${config.API_VERSION}/${config.BUSINESS_PHONE}/messages`, headers: { Authorization: `Bearer ${config.API_TOKEN}`, }, data: { messaging_product: 'whatsapp', status: 'read', message_id: messageId, }, }); } catch (error) { console.error('Error marking message as read:', error); } } } export default new WhatsAppService(); ``````js import whatsappService from './whatsappService.js'; class MessageHandler { async handleIncomingMessage(message) { const isTypeText = message?.type === 'text' if (message?.text.body.includes('img')) { const content = { image: { link: "https://generative-ai-ultisaer.s3.sa-east-1.amazonaws.com/images/breaking_free_from_chains_converted.jpg", caption: "Cosmic Void Darkness" } } await whatsappService.sendMessage({ to: message.from, type: 'image', content}) await whatsappService.markAsRead(message.id); return } if (isTypeText) { const content = { text: { body: `Echo: ${message.text.body}` } } await whatsappService.sendMessage({ to: message.from, type: 'text', content}); await whatsappService.markAsRead(message.id); return } } } export default new MessageHandler(); ```Lo que se puede hacer es que al enviar un mensaje la responsabilidad caiga en el messageHandler haciendo mas modular y permitiendo enviar imgs y videos ![](https://static.platzi.com/media/user_upload/image-42f6eadc-cd29-4291-9410-20909c4c9aed.jpg)
Sigo sin poder verlo, en el iPad, alguno le pasa lo mismo. Se queda el video en negro y no se ve ningún capítulo