0
0

More than 3 years have passed since last update.

LINE Developerの管理画面の「検証」ボタンからの接続確認を成功させる

Posted at

管理画面の「検証」ボタンの場所

この先のページの

Image from Gyazo

これですね

今までは成功したり、しなかったり…

今までのコードではこんな感じに接続確認のときの通信を判断していました。
(一部抜粋)

app.post('/webhook', line.middleware(config), (req, res) => {
    console.log(req.body.events);

    //ここのif分はdeveloper consoleの"接続確認"用なので削除して問題ないです。
    if(req.body.events[0].replyToken === '00000000000000000000000000000000' && req.body.events[1].replyToken === 'ffffffffffffffffffffffffffffffff'){
        res.send('Hello LINE BOT!(POST)');
        console.log('疎通確認用');
        return; 
    }

    Promise
      .all(req.body.events.map(handleEvent))
      .then((result) => res.json(result));
});

ちょっと前(2020年9月くらい?)では、成功したりしなかったりであまりあてにしてなかったでした

すると最近(2020年11月現在)、まったく成功しなくなりました

ただ、その検証以外は普通に動くし、そのif文消したら消したで普通に検証成功するのでまぁいいやと思ったのですが、今回これを解消してみようとして、成功しましたので共有します

検証成功したソースコード

完成コードですが、チャンネルシークレットやアクセストークンはそれぞれ置き換えお願いします

'use strict';

const express = require('express');
const line = require('@line/bot-sdk');
const PORT = process.env.PORT || 3000;

const config = {
    channelSecret: '作成したBOTのチャンネルシークレット',
    channelAccessToken: '作成したBOTのチャンネルアクセストークン'
};

const app = express();

app.get('/', (req, res) => res.send('Hello LINE BOT!(GET)')); //ブラウザ確認用(無くても問題ない)
app.post('/webhook', line.middleware(config), (req, res) => {
    console.log(req.body.events);

    // 空っぽの場合、検証ボタンをクリックしたときに飛んできた"接続確認"用
    if (req.body.events.length == 0) {
      res.send('Hello LINE BOT! (HTTP POST)'); // LINEサーバーに返答します
      console.log('検証イベントを受信しました!'); // ターミナルに表示します
      return; // これより下は実行されません
    }

    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 //実際に返信の言葉を入れる箇所
  });
}

app.listen(PORT);
console.log(`Server running at ${PORT}`);

受け取るデータの中のeventsは、検証時空っぽでした。

また、以前は成功したりしなかったりでしたが、ほぼほぼ検証が正確にできていそうでした!

こうすることで、検証ボタンからの通信か、普通にBOTに話しかけた通信かがわかるようになりました。

0
0
0

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
0
0