whatsapp-cloud-api
Whatsapp Cloud API를 사용하여 봇을 생성하고 메시지를 보내고 받기 위한 Node.js 라이브러리입니다.
내장 Typescript 선언이 포함되어 있습니다.
이 프로젝트는 이제 보관되었습니다 . 자세한 내용은 여기를 참조하세요.
npm 사용:
npm i whatsapp-cloud-api
원사 사용:
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 ) ;
}
} ) ( ) ;
다른 메시지 유형 보내기(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' ) ;
맞춤형 익스프레스 서버(자세한 내용은 아래 참조):
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 ( ) ) ,
} ,
} ) ;
다른 메시지 유형 듣기(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!' ) ;
} ) ;
기본적으로 whatsapp 관련 요청의 엔드포인트는 /webhook/whatsapp
입니다. 즉, 로컬에서는 URL이 http://localhost/webhook/whatsapp
이 됩니다.
역방향 프록시를 사용하여 서버를 공개적으로 사용할 수 있도록 할 수 있습니다. 이에 대한 예는 ngrok입니다.
튜토리얼에서 자세한 내용을 읽을 수 있습니다.
위의 구현은 들어오는 메시지를 수신하는 Express 서버를 생성합니다. 앞으로 다른 유형의 서버를 지원할 계획이 있을 수 있습니다(PR을 환영합니다! :)).
다음과 같이 포트를 변경할 수 있습니다.
await bot . startExpressServer ( {
port : 3000 ,
} ) ;
기본적으로 모든 요청은 POST|GET /webhook/whatsapp
엔드포인트에 의해 처리됩니다. 이를 아래와 같이 변경할 수 있습니다.
await bot . startExpressServer ( {
webhookPath : `/custom/webhook` ,
} ) ;
참고: 앞에 /
; 즉, custom/whatsapp
사용하지 마세요; 대신 /custom/whatsapp
사용하세요.
애플리케이션에서 이미 Express 서버를 실행하고 있는 경우 아래와 같이 이를 사용하여 새 서버를 만드는 것을 피할 수 있습니다.
// your code...
import express from 'express' ;
const app = express ( ) ;
...
// use the `app` variable below:
await bot . startExpressServer ( {
app ,
} ) ;
미들웨어를 추가하려면:
import cors from 'cors' ;
await bot . startExpressServer ( {
useMiddleware : ( app ) => {
app . use ( cors ( ) ) ,
} ,
} ) ;
전체 맞춤형 설정:
import cors from 'cors' ;
await bot . startExpressServer ( {
webhookVerifyToken : 'my-verification-token' ,
port : 3000 ,
webhookPath : `/custom/webhook` ,
useMiddleware : ( app ) => {
app . use ( cors ( ) ) ,
} ,
} ) ;
on()
리스너이 라이브러리는 단일 프로세스 pubsub를 사용합니다. 즉, 분산 Kubernetes 클러스터와 같은 다중 인스턴스 클러스터에 배포하는 경우 제대로 작동하지 않습니다. 앞으로 redis와 같은 외부 저장소에 저장할 수 있는 pubsub 참조를 내보내거나 지원할 계획이 있을 수 있습니다(홍보 환영합니다! :)).
# 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
프로젝트 루트에 .env 파일을 만듭니다.
FROM_PHONE_NUMBER_ID=""
ACCESS_TOKEN=""
VERSION=""
TO=""
WEBHOOK_VERIFY_TOKEN=""
WEBHOOK_PATH=""
node-telegram-bot-api에서 영감을 받은 라이브러리 API입니다.
모든 PR이 공개되어 있습니다.