Firebase에서 Node.js를 움직여 LINE BOT 만들기
정적 사이트만이라고 생각하면, 대단하네요. (시계하지 않았을 뿐)
준비
이번은 먼저 프로젝트가 있던 곳에서 시작했으므로 이 순서 소개로 합니다.
Firebase CLI 설치
npm i -g firebase-tools
CLI로 로그인
firebase login
? Allow Firebase to collect anonymous CLI usage and err
or reporting information? [Y/n]
질문이 오기 때문에
Y
브라우저가 열리므로 로그인할 계정을 선택하여 진행합니다.

・
・
・
✔ Success! Logged in as [email protected]
같은 표시가 나오면 로그인 성공입니다.
로컬로 프로젝트 만들기
firebase init functions
뭔가 멋진 표시 나옵니다.

어떤 프로젝트에서 시작할지 선택할 수 있습니다.
forlinebot
라는 이름으로 firebase 프로젝트를 만들었으므로 중간의 forlinebot
이름을 선택합니다.
이 후에는 기본적으로 Enter로 진행해 괜찮다고 생각합니다.
이번에는 JavaScript로 갑니다.

그대로 Enter로 진행했기 때문에 N인가?

그대로 Enter로 진행했기 때문에 Yes
Do you want to install dependencies with npm now? Yes
그러면 이런 느낌의 폴더와 파일이 완성됩니다.

functionsフォルダ
, .firebaserc
, .gitignore
및 firebase.json
가 생성되어 functions 폴더에 응용 프로그램 템플릿을 만들 수 있습니다.Express 및 LINE BOT SDK로 BOT 작성 준비
종속 모듈을 설치합니다.
functions
폴더로 이동하여 설치합니다.cd functions
npm i --save @line/bot-sdk express
index.js
를 다음 내용으로 다시 씁니다. 이 기사 을 참고로 channelSecret
와 channelAccessToken
에 값을 넣자.index.js
'use strict';
const functions = require('firebase-functions');
const express = require('express');
const line = require('@line/bot-sdk');
const config = {
channelSecret: '',
channelAccessToken: ''
};
const app = express();
app.post('/webhook', line.middleware(config), (req, res) => {
console.log(req.body.events);
Promise
.all(req.body.events.map(handleEvent))
.then((result) => res.json(result));
});
const client = new line.Client(config);
async function handleEvent(event) {
if (event.type !== 'message' || event.message.type !== 'text') {
return Promise.resolve(null);
}
return client.replyMessage(event.replyToken, {
type: 'text',
text: event.message.text //実際に返信の言葉を入れる箇所
});
}
exports.app = functions.https.onRequest(app);
firebase.json
를 다음으로 다시 씁니다.firebase.json
{
"hosting": {
"public": "./",
"rewrites": [{
"source": "/webhook",
"function": "app"
}],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
응용 프로그램 시작 및 ngrok에서 작동 확인
아래에서 local 서버를 시작합니다.
firebase serve --only functions,hosting
그러면
localhost:5000
서버가 시작됩니다.서버 측만이므로,
functions
의 지정만으로 좋을까 생각해 express의 이 방법이라고 hosting
도 지정하지 않으면 에러가 나왔습니다. 별로 쫓지 않습니다.이 기사 을 참고로 ngrok에서 5000번 포트로의 터널링 서버도 기동합시다.
ngrok http 5000

게시된 ngrok URL을 LINE Developers 채널 설정에서 Webhook URL로 설정합니다.

여기까지 문제가 없으면, 대답 BOT이 되어 있다고 생각합니다.

배포
async/await를 사용하고 싶으므로 서버의 Node.js 버전을 최신( 현시점에서 8계인 것 같다 )으로 합니다.
functions/package.json
에 다음 engines 사양을 추가합니다."engines": {"node": "8"}
이전 명령의 serve 부분을 deploy로 변경하여 실행합니다.
firebase deploy --only functions,hosting
=== Deploying to 'forlinebot-xxxx'...
i deploying functions, hosting
i functions: ensuring necessary APIs are enabled...
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (27.22 KB) for uploading
✔ functions: functions folder uploaded successfully
・
・
・
・
✔ Deploy complete!
Please note that it can take up to 30 seconds for your updated functions to propagate.
Project Console: https://console.firebase.google.com/project/forlinebot-xxxx/overview
Hosting URL: https://forlinebot-xxxx.firebaseapp.com
첫회는 조금 시간이 걸린 인상입니다만, 2회째 이후는 상당히 빨리 배치할 수 있었습니다.
여기에서 생성된 주소( htps : // 홉 x. 흠뻑 빠지다 p. 이 m )를 LINE Developers의 Webhook URL로 다시 설정하면 완료됩니다.

잡감
Firebase 전혀 워치 하고 있지 않았지만 편리하지.
참고
Reference
이 문제에 관하여(Firebase에서 Node.js를 움직여 LINE BOT 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/n0bisuke/items/909881c8866e3f2ca642텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)