Node.js 및 Twilio를 사용하여 10 분 내에 WhatsApp 봇 빌드
본문
WhatsApp은 15억 이상의 사용자가 친구 및 가까운 사람들과 연락을 유지하도록 돕습니다. 기업은 이를 통해 채팅을 통해 가장 자연스럽게 많은 사용자에게 접근 할 수 있습니다. 이 자습서에서는 Node.js 및 Twilio API를 사용하여 WhatsApp 봇을 만듭니다.
봇은 Google 검색 API를 사용하여 WhatsApp에서 Google의 모든 항목을 직접 검색 할 수 있습니다.
시작하기
첫 번째 단계는 맞춤 Google 검색 엔진을 만드는 것입니다.
맞춤 검색 JSON API에는 API 키를 사용해야 하므로 키를 가져 오겠습니다. 여기를 클릭하십시오
키 받기(GET A KEY)를 클릭하십시오 - 나중에 필요할 것이므로 프로젝트를 생성하고 API 키를 복사하십시오.
다음 단계는 맞춤 검색 엔진을 설정하는 것입니다 여기를 클릭하십시오
- 추가 클릭
검색하려는 웹 사이트와 이름을 입력하고 생성을 클릭하십시오
- 제어판을 클릭하십시오
- 검색 엔진 ID를 참고하십시오. 나중에 필요합니다.
‘전체 웹 검색’버튼을 켜십시오. 그러면 보다 자세한 검색이 가능합니다.
Twilio 샌드 박스 환경 설정
다음 단계는 Twilio에서 샌드 박스 환경을 설정하는 것입니다. 아래 단계를 따르십시오.
- Twilio 계정이 없는 경우 생성
- 계정을 만들고 확인한 후 계정에 로그인하고 탐색 모음에서 콘솔을 클릭하십시오.
- 새 프로젝트 작성을 클릭하고 제품> 프로그램 가능 SMS를 선택한 후 계속을 클릭하십시오.
- 계정 SID 및 AUTH TOKEN을 기록해 두십시오
마지막 단계는 WhatsApp Sandbox 환경을 설정하는 것입니다. 여기를 클릭하십시오
- WhatsApp 메시지를 페이지의 Twilio 번호로 보내 샌드 박스에 연결하십시오.
가장 어려운 부분이라고 믿어주세요. 이제 사업을 시작하겠습니다.
프로젝트의 디렉토리를 만들어 봅시다.
터미널에서 mkdir whatsapp-bot을 실행하거나 프로젝트의 디렉토리를 수동으로 작성하십시오.
프로젝트 디렉토리 안에 .env 파일을 만들고 다음을 입력하십시오.
- Twilio의 계정 SID 및 AUTH 토큰
- Google API 키 추가
- 검색 엔진 ID
다음 종속성으로 package.json을 작성하십시오.
{ | |
"name": "whatsapp-bot", | |
"version": "1.0.0", | |
"description": "A whatspp bot that uses twilio ", | |
"main": "index.js", | |
"scripts": { | |
"start": "babel-node server/server.js", | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "Ekpang Michael", | |
"license": "ISC", | |
"dependencies": { | |
"cors": "2.8.5", | |
"dotenv": "8.0.0", | |
"express": "^4.16.3", | |
"googleapis": "^42.0.0", | |
"twilio": "^4.6.0" | |
}, | |
"devDependencies": { | |
"@babel/cli": "7.5.5", | |
"@babel/core": "7.5.5", | |
"@babel/node": "^7.5.5", | |
"@babel/preset-env": "^7.5.5" | |
}, | |
"engines": { | |
"node": "8.x" | |
} | |
} |
.babelrc 파일을 작성하고 이 코드를 추가하십시오.
{ | |
"presets": ["@babel/preset-env"] | |
} |
npm install을 실행하여 모든 종속성을 설치하십시오.
이 코드를 server/server.js 파일에 복사하여 붙여 넣기
import express from 'express'; | |
import cors from 'cors'; | |
import v1Routes from './routes'; | |
const app = express(); | |
const { PORT = 3000 } = process.env; | |
app.use(cors()); | |
app.use( | |
express.urlencoded({ | |
extended: false | |
}) | |
); | |
app.use(express.json()); | |
app.use(v1Routes); | |
// catch 404 and forward to error handler | |
app.use((req, res, next) => { | |
const err = new Error('Not Found'); | |
err.status = 404; | |
next(err); | |
}); | |
app.use((err, req, res, next) => { | |
res.status(err.status || 500).json({ | |
errors: { | |
message: err.message | |
} | |
}); | |
}); | |
app.listen(PORT, () => console.log(`App Listening on port ${PORT}`)); | |
export default app; |
여기서는 포트 3000에서 실행되는 빠른 서버를 만들고 있습니다.
폴더 구조는 다음과 같아야 합니다
npm start를 실행하여 서버를 시작하면 앱이 포트 3000에서 실행되기 시작합니다.
다음으로 ngrok을 다운로드하겠습니다. 로컬 서버를 인터넷에서 공개적으로 액세스하려면 ngrok이 필요합니다.
- 디렉토리 내에서 압축 풀기
- 다른 터미널에서 ./ngrok http 3000을 실행하십시오.
ngrok가 온라인 상태로 시작된 것을 볼 수 있습니다.
- 새 ngrok 서버 URL을 복사하고 WhatsApp 샌드 박스로 돌아가서 웹훅 URL로 추가합니다.
경로가 어떻게 구성되는지 api/v1/incoming 참고
그런 다음 컨트롤러 폴더 내에 WhatsappBot.js 파일을 만듭니다.
폴더 구조는 다음과 같아야 합니다
다음으로 Google API 및 Twilio 라이브러리를 WhatsappBot.js로 가져옵니다.
import { google } from 'googleapis'; | |
import dotenv from 'dotenv'; | |
import twilio from 'twilio'; | |
dotenv.config(); |
계정 ID와 인증 토큰을 전달하여 환경 변수를 로드하고 Twilio 계정을 초기화합시다.
const { | |
SID: accountSid, | |
KEY: TwilloAuthToken, | |
APIKEY: googleApiKey, | |
CX: cx | |
} = process.env; | |
twilio(accountSid, TwilloAuthToken); | |
const { MessagingResponse } = twilio.twiml; | |
const customsearch = google.customsearch('v1'); |
아래 이미지에서 MessgingResponse 객체를 초기화하고 사용자가 req.body.Body에서 보내는 쿼리를 가져 와서 Google customsearch 메소드를 호출하고 options 매개 변수를 전달합니다.
그런 다음 검색 결과에서 첫 번째 컨텐츠를 가져 와서 사용자에게 다시 보냅니다.
class WhatsappBot { | |
/** | |
* @memberof WhatsappBot | |
* @param {object} req - Request sent to the route | |
* @param {object} res - Response sent from the controller | |
* @param {object} next - Error handler | |
* @returns {object} - object representing response message | |
*/ | |
static async googleSearch(req, res, next) { | |
const twiml = new MessagingResponse(); | |
const q = req.body.Body; | |
const options = { cx, q, auth: googleApiKey }; | |
try { | |
const result = await customsearch.cse.list(options); | |
const firstResult = result.data.items[0]; | |
const searchData = firstResult.snippet; | |
const link = firstResult.link; | |
twiml.message(`${searchData} ${link}`); | |
res.set('Content-Type', 'text/xml'); | |
return res.status(200).send(twiml.toString()); | |
} catch (error) { | |
return next(error); | |
} | |
} | |
} |
아래의 전체 코드를 참조하십시오.
import { google } from 'googleapis'; | |
import dotenv from 'dotenv'; | |
import twilio from 'twilio'; | |
dotenv.config(); | |
const { | |
SID: accountSid, | |
KEY: TwilloAuthToken, | |
APIKEY: googleApiKey, | |
CX: cx | |
} = process.env; | |
twilio(accountSid, TwilloAuthToken); | |
const { MessagingResponse } = twilio.twiml; | |
const customsearch = google.customsearch('v1'); | |
/** | |
* @class WhatsappBot | |
* @description class will implement bot functionality | |
*/ | |
class WhatsappBot { | |
/** | |
* @memberof WhatsappBot | |
* @param {object} req - Request sent to the route | |
* @param {object} res - Response sent from the controller | |
* @param {object} next - Error handler | |
* @returns {object} - object representing response message | |
*/ | |
static async googleSearch(req, res, next) { | |
const twiml = new MessagingResponse(); | |
const q = req.body.Body; | |
const options = { cx, q, auth: googleApiKey }; | |
try { | |
const result = await customsearch.cse.list(options); | |
const firstResult = result.data.items[0]; | |
const searchData = firstResult.snippet; | |
const link = firstResult.link; | |
twiml.message(`${searchData} ${link}`); | |
res.set('Content-Type', 'text/xml'); | |
return res.status(200).send(twiml.toString()); | |
} catch (error) { | |
return next(error); | |
} | |
} | |
} | |
export default WhatsappBot; |
경로 설정
- 경로 폴더 안에 search.js 파일 만들기
여기서 WhatsAppbot 컨트롤러를 가져 와서 포스트 라우트를 설정합니다
import { Router } from 'express'; | |
import WhatsappBot from '../controllers/WhatsappBot'; | |
const botRouter = Router(); | |
botRouter.post('/incoming', WhatsappBot.googleSearch); | |
export default botRouter; |
경로 폴더 안에 index.js를 만들고 검색 경로를 가져옵니다
import { Router } from 'express'; | |
import botRouter from './search'; | |
const v1Router = Router(); | |
v1Router.use('/api/v1', botRouter); | |
export default v1Router; |
서버를 다시 시작하고 WhatsApp을 통해 엔드 포인트로 메시지를 보내십시오.
모든 것이 잘 진행되면 응답을 다시 받아야 합니다.
축하합니다. 첫 번째 WhatsApp 봇을 만들었습니다.