whatsapp-cloud-api
é uma biblioteca Node.js para criação de bots e envio/recebimento de mensagens usando a API Whatsapp Cloud.
Contém declarações Typescript integradas.
Este projeto agora está arquivado . Por favor, leia mais aqui.
Usando npm:
npm i whatsapp-cloud-api
Usando fio:
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 ) ;
}
} ) ( ) ;
Envio de outros tipos de mensagens (leia mais na referência da 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 expresso personalizado (leia mais abaixo):
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 ( ) ) ,
} ,
} ) ;
Ouvindo outros tipos de mensagens (leia mais na referência da 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!' ) ;
} ) ;
Por padrão, o endpoint para solicitações relacionadas ao WhatsApp será: /webhook/whatsapp
. Isso significa que localmente, sua URL será: http://localhost/webhook/whatsapp
.
Você pode usar um proxy reverso para disponibilizar o servidor publicamente. Um exemplo disso é o ngrok.
Você pode ler mais no Tutorial.
A implementação acima cria um servidor expresso para você, por meio do qual ele escuta as mensagens recebidas. Pode haver planos para oferecer suporte a outros tipos de servidores no futuro (RPs são bem-vindos! :)).
Você pode alterar a porta da seguinte maneira:
await bot . startExpressServer ( {
port : 3000 ,
} ) ;
Por padrão, todas as solicitações são tratadas pelo endpoint POST|GET /webhook/whatsapp
. Você pode alterar isso conforme abaixo:
await bot . startExpressServer ( {
webhookPath : `/custom/webhook` ,
} ) ;
Nota: Lembre-se do /
; ou seja, não use custom/whatsapp
; em vez disso, use /custom/whatsapp
.
Se você já estiver executando um servidor expresso em seu aplicativo, poderá evitar a criação de um novo usando-o conforme abaixo:
// your code...
import express from 'express' ;
const app = express ( ) ;
...
// use the `app` variable below:
await bot . startExpressServer ( {
app ,
} ) ;
Para adicionar middleware:
import cors from 'cors' ;
await bot . startExpressServer ( {
useMiddleware : ( app ) => {
app . use ( cors ( ) ) ,
} ,
} ) ;
Configuração personalizada completa:
import cors from 'cors' ;
await bot . startExpressServer ( {
webhookVerifyToken : 'my-verification-token' ,
port : 3000 ,
webhookPath : `/custom/webhook` ,
useMiddleware : ( app ) => {
app . use ( cors ( ) ) ,
} ,
} ) ;
on()
Esta biblioteca usa um único processo pubsub, o que significa que não funcionará bem se você estiver implantando em clusters de várias instâncias, por exemplo, clusters Kubernetes distribuídos. No futuro, pode haver planos para exportar/suportar uma referência pubsub que pode ser armazenada em armazenamento externo, por exemplo, redis (PRs são bem-vindos! :)).
# 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
Crie um arquivo .env na raiz do seu projeto:
FROM_PHONE_NUMBER_ID=""
ACCESS_TOKEN=""
VERSION=""
TO=""
WEBHOOK_VERIFY_TOKEN=""
WEBHOOK_PATH=""
API de biblioteca inspirada em node-telegram-bot-api.
Todo e qualquer PR está aberto.