前回の記事ではobnizに格言を表示しました。
今回は格言を表示してくれるLineBotを作成しました。
流れ
まずはこちらの記事を参考にLine Botを作ります。
おうむ返しまで完了させます。
server.js
を変更するので一度、control + C
でnode 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がランダムで出力されます。
こんな感じです〜。
ありがとうございました!