4
0

More than 3 years have passed since last update.

【初心者チャレンジ】楽天検索 LINE BOT2 Herokuで実装

Posted at

axios と javascript を使った楽天検索 LINEBOTをHerokuで実装

今週は先日作成した楽天で本を検索できるBOTなど、今まではngrokを使用してトンネリングし
試作していましたが、ついにHerokuを使って実装してみたいと思います。

参考資料

【資料1】1時間でLINE BOTを作るハンズオン (資料+レポート) in Node学園祭2017 #nodefest
【資料2】【初心者チャレンジ】楽天検索 LINE BOT

ラインボットの作り方は【資料1】
楽天検索botの作り方は【資料2】を参考に。

環境

Node.js v10.16.3
Windows 10 pro
Visual Studio Code v1.39.1

概要

image.png

フォルダを作成し、中に >index.js:作成したラインボットを動かすコード
            >package-lock.json:npm init -yで作成される
            >package.json:npm init -yで作成される
             インストールしたライブラリデータ等のパッケージが登録されている
            >Procfile:Herokuを起動するのに必要なファイル

の4ファイルを作成し、Herokuでラインボットと繋げる。フォルダ名はスペースは使えないので気を付けましょう。
今回のコードを起動必要なライブラリは

npm init -y
npm i @line/bot-sdk express  
npm i --save axios  
npm i body-parser express                   

をそれぞれターミナルに入力し、インストール。

index.js


'use strict';

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

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


function handleEvent(event) {
  if (event.type !== 'message' || event.message.type !== 'text') {
    return Promise.resolve(null);
  }
  console.log("test1");


  let mes = ''
  if(event.message.text === '本教えて!'){
    console.log("test2");


    mes = '検索したいタイトルを教えてね'; //本を教えてと言われたらタイトルを聞く
  }else{
    console.log("test3");


    mes = event.message.text; //イベントメッセージでない場合
   getBook(event.source.userId , event.message.text);//getbook でAPI取得に向かう

  }
  console.log("test4 mes = " + mes);

  return client.replyMessage(event.replyToken, {
    type: 'text',
    text: mes
  });
}


const getBook = async (userId, booktitle) => {
  const rakutenURL = 'https://app.rakuten.co.jp/services/api/BooksBook/Search/20170404?format=json&booksGenreId=001004008&count=3&applicationId=';
  const titleStr   = '&title='+ booktitle ;// イベントメッセージ以外をここに入れたい

  let apiUrl = encodeURI( rakutenURL + titleStr ); // URLエンコード
  const res = await axios.get( apiUrl );
  const items = res.data.Items;

  for (var item in items) {
    console.log(items[item].Item.title ); // タイトル
    console.log(items[item].Item.mediumImageUrl );
    /*
    console.log(items[item].Item.title ); // タイトル
    console.log(items[item].Item.titleKana ); // タイトルカナ
    console.log(items[item].Item.seriesName );
    console.log(items[item].Item.seriesNameKana );
    console.log(items[item].Item.author );
    console.log(items[item].Item.authorKana );
    console.log(items[item].Item.itemCaption );  
    */

    res.data.name
      await client.pushMessage(userId, {
      type: 'text',
      text: items[item].Item.title + '作者:' + items[item].Item.author  + '\n=================《あらすじ》==========\n' + items[item].Item.itemCaption,
    });
  }
}


app.listen(PORT);
//一番上段のexpressのコードとのセット。ポートとつなぎます。
console.log(`Server running at ${PORT}`);
//つながれたらTerminalに記載します。

Procfile

web: node index.js

こちら、Procfileをindex.jsと同じフォルダに置かなければHerokuをうまく使えないようですので、作成。

Herokuの実行

あとはHerokuを起動させてWebhookでLINEBOTで繋げる。

完成

image.png

本のタイトルからあらすじを紹介してくれるLINEBOTができました!!
また適宜更新されてゆくかともいますが
宜しければ一度試しにお使いいただければなと思います。
宜しくお願いします!!

image.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