whatsapp-cloud-api
es una biblioteca de Node.js para crear bots y enviar/recibir mensajes utilizando la API de Whatsapp Cloud.
Contiene declaraciones mecanografiadas integradas.
Este proyecto ahora está archivado . Por favor lea más aquí.
Usando npm:
npm i whatsapp-cloud-api
Usando hilo:
yarn add whatsapp-cloud-api
import { createBot } from 'whatsapp-cloud-api' ;
// or if using require:
// const { createBot } = require('whatsapp-cloud-api');
( async ( ) => {
try {
// replace the values below
const from = 'YOUR_WHATSAPP_PHONE_NUMBER_ID' ;
const token = 'YOUR_TEMPORARY_OR_PERMANENT_ACCESS_TOKEN' ;
const to = 'PHONE_NUMBER_OF_RECIPIENT' ;
const webhookVerifyToken = 'YOUR_WEBHOOK_VERIFICATION_TOKEN' ;
// Create a bot that can send messages
const bot = createBot ( from , token ) ;
// Send text message
const result = await bot . sendText ( to , 'Hello world' ) ;
// Start express server to listen for incoming messages
// NOTE: See below under `Documentation/Tutorial` to learn how
// you can verify the webhook URL and make the server publicly available
await bot . startExpressServer ( {
webhookVerifyToken ,
} ) ;
// Listen to ALL incoming messages
// NOTE: remember to always run: await bot.startExpressServer() first
bot . on ( 'message' , async ( msg ) => {
console . log ( msg ) ;
if ( msg . type === 'text' ) {
await bot . sendText ( msg . from , 'Received your text message!' ) ;
} else if ( msg . type === 'image' ) {
await bot . sendText ( msg . from , 'Received your image!' ) ;
}
} ) ;
} catch ( err ) {
console . log ( err ) ;
}
} ) ( ) ;
Envío de otros tipos de mensajes (lea más en la referencia de API):
// Send image
const result = await bot . sendImage ( to , 'https://picsum.photos/200/300' , {
caption : 'Random jpg' ,
} ) ;
// Send location
const result = await bot . sendLocation ( to , 40.7128 , - 74.0060 , {
name : 'New York' ,
} ) ;
// Send template
const result = await bot . sendTemplate ( to , 'hello_world' , 'en_us' ) ;
Servidor express personalizado (lea más a continuación):
import cors from 'cors' ;
// Create bot...
const bot = createBot ( ... ) ;
// Customize server
await bot . startExpressServer ( {
webhookVerifyToken : 'my-verification-token' ,
port : 3000 ,
webhookPath : `/custom/webhook` ,
useMiddleware : ( app ) => {
app . use ( cors ( ) ) ,
} ,
} ) ;
Escuchar otros tipos de mensajes (lea más en la referencia de API):
const bot = createBot ( ... ) ;
await bot . startExpressServer ( { webhookVerifyToken } ) ;
// Listen to incoming text messages ONLY
bot . on ( 'text' , async ( msg ) => {
console . log ( msg ) ;
await bot . sendText ( msg . from , 'Received your text!' ) ;
} ) ;
// Listen to incoming image messages ONLY
bot . on ( 'image' , async ( msg ) => {
console . log ( msg ) ;
await bot . sendText ( msg . from , 'Received your image!' ) ;
} ) ;
De forma predeterminada, el punto final para las solicitudes relacionadas con WhatsApp será: /webhook/whatsapp
. Esto significa que localmente, su URL será: http://localhost/webhook/whatsapp
.
Puede utilizar un proxy inverso para que el servidor esté disponible públicamente. Un ejemplo de esto es ngrok.
Puedes leer más en el Tutorial.
La implementación anterior crea un servidor rápido a través del cual escucha los mensajes entrantes. Es posible que haya planes para admitir otros tipos de servidores en el futuro (¡los RP son bienvenidos! :)).
Puede cambiar el puerto de la siguiente manera:
await bot . startExpressServer ( {
port : 3000 ,
} ) ;
De forma predeterminada, todas las solicitudes son manejadas por el punto final POST|GET /webhook/whatsapp
. Puede cambiar esto como se muestra a continuación:
await bot . startExpressServer ( {
webhookPath : `/custom/webhook` ,
} ) ;
Nota: Recuerde el encabezado /
; es decir, no utilice custom/whatsapp
; en su lugar utilice /custom/whatsapp
.
Si ya está ejecutando un servidor Express en su aplicación, puede evitar crear uno nuevo usándolo de la siguiente manera:
// your code...
import express from 'express' ;
const app = express ( ) ;
...
// use the `app` variable below:
await bot . startExpressServer ( {
app ,
} ) ;
Para agregar middleware:
import cors from 'cors' ;
await bot . startExpressServer ( {
useMiddleware : ( app ) => {
app . use ( cors ( ) ) ,
} ,
} ) ;
Configuración personalizada completa:
import cors from 'cors' ;
await bot . startExpressServer ( {
webhookVerifyToken : 'my-verification-token' ,
port : 3000 ,
webhookPath : `/custom/webhook` ,
useMiddleware : ( app ) => {
app . use ( cors ( ) ) ,
} ,
} ) ;
on()
oyenteEsta biblioteca utiliza un pubsub de proceso único, lo que significa que no funcionará bien si está implementando en clústeres de múltiples instancias, por ejemplo, clústeres distribuidos de Kubernetes. En el futuro, es posible que haya planes para exportar/soportar una referencia de pubsub que se pueda almacenar en un almacenamiento externo, por ejemplo, redis (¡los PR son bienvenidos! :)).
# install npm modules
npm i
# eslint
npm run lint
# typescript check
npm run ts-check
# test
# # Read 'Local Testing' below before running this
npm t
# build
npm run build
Cree un archivo .env en la raíz de su proyecto:
FROM_PHONE_NUMBER_ID=""
ACCESS_TOKEN=""
VERSION=""
TO=""
WEBHOOK_VERIFY_TOKEN=""
WEBHOOK_PATH=""
API de biblioteca inspirada en node-telegram-bot-api.
Todos y cada uno de los RP están abiertos.