LoginSignup
5
2

More than 3 years have passed since last update.

LINE botをFirebaseで動かしたらつまづいた

Posted at

FirebaseとかNode.jsとか全く触ったことないけど、なんとなくLINE bot触りたくなったので色々見ながら動かしてみた。

散々エラー出たので同じことにならないようにメモ。

環境

  • Node.js v10.15.3
  • npm v6.4.1
  • firebase-tools v6.10.0
  • Windows10(Macでも動いた)

(2019/05/24時点)

構築手順

手順は他の参考にした記事が下記。
同じことを書いても仕方ないので。

行き詰まったところ

line.middlewareをapp.postより前にしないとエラー?ワーニング?が出てしまってダメだった。
シグネチャって言われてもどうしろと状態。

(node:3664) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be one of type string, TypedArray, or DataView. Received type object
      at Hmac.update (internal/crypto/hash.js:58:11)
      at Object.validateSignature [as default] (C:\mylinebot\functions\node_modules\@line\bot-sdk\dist\validate-signature.js:37:10)
      at getBody.then.body (C:\mylinebot\functions\node_modules\@line\bot-sdk\dist\middleware.js:37:46)
      at process._tickCallback (internal/process/next_tick.js:68:7)

最終的なindex.js

前述の参考ページを見て、line.middleware(config)を前に持っていった。

index.js
'use strict';

const functions = require('firebase-functions');
const express = require('express');
const line = require('@line/bot-sdk');

const config = { 
    channelSecret: '', // LINE DeveloperからChannel Secretをコピペ
    channelAccessToken: '' // LINE Developerからアクセストークンをコピペ
};

const app = express();

let middle = line.middleware(config); //★ここ
app.post('/webhook', (req, res) => {

  console.log(req.body.events);
  Promise
    .all(req.body.events.map(handleEvent))
    .then((result) => res.json(result))
    .catch((result) => console.log('error!!!'));
});

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);

リンクやメモ

ngrokでトンネル

$ npm i -g ngrok
$ npm http 5000

firebase

$ firebase serve --only functions,hosting // ngrokで試験
$ firebase deploy --only functions,hosting // デプロイ
5
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2