whatsapp-cloud-api
est une bibliothèque Node.js permettant de créer des robots et d'envoyer/recevoir des messages à l'aide de l'API Whatsapp Cloud.
Contient des déclarations Typescript intégrées.
Ce projet est maintenant archivé . Veuillez en lire davantage ici.
Utilisation de npm :
npm i whatsapp-cloud-api
Utiliser du fil :
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 ) ;
}
} ) ( ) ;
Envoi d'autres types de messages (en savoir plus dans la référence 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' ) ;
Serveur express personnalisé (en savoir plus ci-dessous) :
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 ( ) ) ,
} ,
} ) ;
Écoute d'autres types de messages (en savoir plus dans la référence 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!' ) ;
} ) ;
Par défaut, le point de terminaison des requêtes liées à WhatsApp sera : /webhook/whatsapp
. Cela signifie que localement, votre URL sera : http://localhost/webhook/whatsapp
.
Vous pouvez utiliser un proxy inverse pour rendre le serveur accessible au public. Ngrok en est un exemple.
Vous pouvez en savoir plus sur le didacticiel.
L'implémentation ci-dessus crée pour vous un serveur express via lequel elle écoute les messages entrants. Il pourrait être prévu de prendre en charge d'autres types de serveurs à l'avenir (les PR sont les bienvenus ! :)).
Vous pouvez modifier le port comme suit :
await bot . startExpressServer ( {
port : 3000 ,
} ) ;
Par défaut, toutes les requêtes sont traitées par le point de terminaison POST|GET /webhook/whatsapp
. Vous pouvez modifier cela comme ci-dessous :
await bot . startExpressServer ( {
webhookPath : `/custom/webhook` ,
} ) ;
Remarque : N'oubliez pas le début /
; c'est à dire, n'utilisez pas custom/whatsapp
; utilisez plutôt /custom/whatsapp
.
Si vous exécutez déjà un serveur express dans votre application, vous pouvez éviter d'en créer un nouveau en l'utilisant comme ci-dessous :
// your code...
import express from 'express' ;
const app = express ( ) ;
...
// use the `app` variable below:
await bot . startExpressServer ( {
app ,
} ) ;
Pour ajouter un middleware :
import cors from 'cors' ;
await bot . startExpressServer ( {
useMiddleware : ( app ) => {
app . use ( cors ( ) ) ,
} ,
} ) ;
Configuration entièrement personnalisée :
import cors from 'cors' ;
await bot . startExpressServer ( {
webhookVerifyToken : 'my-verification-token' ,
port : 3000 ,
webhookPath : `/custom/webhook` ,
useMiddleware : ( app ) => {
app . use ( cors ( ) ) ,
} ,
} ) ;
on()
écouteurCette bibliothèque utilise un seul processus pubsub, ce qui signifie qu'elle ne fonctionnera pas bien si vous déployez sur des clusters multi-instances, par exemple des clusters Kubernetes distribués. À l'avenir, il pourrait être prévu d'exporter/supporter une référence pubsub qui peut être stockée dans un stockage externe, par exemple redis (les PR sont les bienvenus ! :)).
# 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
Créez un fichier .env à la racine de votre projet :
FROM_PHONE_NUMBER_ID=""
ACCESS_TOKEN=""
VERSION=""
TO=""
WEBHOOK_VERIFY_TOKEN=""
WEBHOOK_PATH=""
API de bibliothèque inspirée de node-telegram-bot-api.
Tous les PR sont ouverts.