8
5

More than 3 years have passed since last update.

【初心者チャレンジ】楽天検索 LINE BOT

Last updated at Posted at 2019-11-13

axios と javascript を使った楽天検索 LINEBOT

今週も懲りずに初心者チャレンジ。
季節感を出し、読書の秋という事で、何か簡単に本を検索できるようにしたいなと思いました。

参考資料

【資料1】1時間でLINE BOTを作るハンズオン (資料+レポート) in Node学園祭2017 #nodefest
【資料2】Nuxt.jsでaxiosを使ってサクッと小さなアプリを作る
【資料3】jQuery 楽天APIを必要最低限で動かす
【資料3】楽天ショッピングAPIをJavaから呼び出す

概要

①【資料1】を参考に LINEBOTを作る
②【資料2、3】を参考に javascriptでaxiosを使って検索するコードを書いて開発
③【資料1】を参考に ngrokで繋ぐ

環境

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

楽天APIを取得する

楽天ショッピングAPI登録をクリックしてアプリ登録する。必須URLは人のURLは使っちゃいけないので自分の適当なサイトで登録。

image.png

API取得はこのURLに繋ぐようです。
また、指定するパラメーターによってURLが変わるので、APIを取得する際にタイトルの所のURLをLINEから書き換えれば良さそう。
テストフォームがあったので早速タイトルを秋で検索。取得データを確認します。

image.png

なぜか“黄緑のネームプレート”というタイトルの本が一番目に出てきました。
秋どこいったw

使用したコード

'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=楽天APIのアプリID';
  const titleStr   = '&title='+ booktitle ;
  // booktitleがラインメッセージで入力した本の名前

  let apiUrl = encodeURI( rakutenURL + titleStr ); 
  // rakutenURL +とtitleStrを足してURLエンコードをつくる

  const res = await axios.get( apiUrl );
  //axiosでURLに取りに行く

  const items = res.data.Items;


  console.log(items[0].Item.title ); // タイトル
  console.log(items[0].Item.titleKana );
  console.log(items[0].Item.seriesName );
  console.log(items[0].Item.seriesNameKana );
  console.log(items[0].Item.author ); // 作者
  console.log(items[0].Item.authorKana );
  console.log(items[0].Item.itemCaption );
  //どんなデータが出力されてきているかターミナルで確認する


   res.data.name
   await client.pushMessage(userId, {
   type: 'text',
   text: items[0].Item.title + '作者:' + items[0].Item.author + '=================《あらすじ》==========' + items[0].Item.itemCaption,
   //リプライで返すパラメーターを指定する。[0]は検索ヒット1番上を指定している

 });
}

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

いい感じに動く!!

image.png

image.png

ちゃんと阿良々木君まででてくる!!嬉しい!!

image.png
作者も付け加えてみました。

結果

本当は画像が欲しい。。。
どんな表紙なのか知りたい。
作家さんからも検索したい。などなど、欲を言えば拡張できる事が
多いと思いますが、今回は楽天APIとaxiosを繋げるという目標が一つ達成できました!!

色々検索していたのですが意外に、楽天とラインボットをjavascriptを使って作っている事例が少ないように思いました。
楽天は普段結構使うので、こういう形でも使えるという事が知れて良かったです。

8
5
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
8
5