4
0

More than 1 year has passed since last update.

LINE Botに格言を表示

Posted at

前回の記事ではobnizに格言を表示しました。

今回は格言を表示してくれるLineBotを作成しました。

流れ

まずはこちらの記事を参考にLine Botを作ります。
おうむ返しまで完了させます。

server.jsを変更するので一度、control + Cnode server.jsを終了させます。

mylinebotフォルダの直下で
npm i axiosを実行します。

そうするとpackage.jsonの中にaxiosが追加されます。

server.jsファイル内の'use strict'の次の行あたりにAPIを叩くための呪文const axios = require('axios');を記載。

コード終わりの方の//実際に返信の言葉を入れる箇所のところに表示させたいAPIの情報を記載。

全体像は次の通り

'use strict';

//APIを叩ける
const axios = require('axios');

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

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

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分は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));
});

const client = new line.Client(config);

async function handleEvent(event) {
  if (event.type !== 'message' || event.message.type !== 'text') {
    return Promise.resolve(null);
  }
  const res = await axios.get('https://api.adviceslip.com/advice'); //APIのURL
  console.log(res.data.slip.advice);

  return client.replyMessage(event.replyToken, {
    type: 'text',
    text: res.data.slip.advice //実際に返信の言葉を入れる箇所
  });
}

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

これでLINE Botになにか話かけると格言のAPIがランダムで出力されます。

スクリーンショット 2021-10-24 22.46.33.png

こんな感じです〜。
ありがとうございました!

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