LoginSignup
5
1

More than 3 years have passed since last update.

ド素人がLINE botを公開してみた

Posted at

プロトアウトスタジオという、プログラミングスクールではなく、プロトタイピングをアウトプットするというスクールに参加し始めた人の記事です。

授業にて、「heroku」というPaaSサービスにソースコードをのせて動かす体験をしました。
サーバとかOSとか、プログラムを動かすための環境づくりに必要な知識をすっ飛ばしていきなりサービスを無料で動かせる時代になっているのですね。

今回の宿題は「HerokuでNode.jsの仕組みをURLを公開しチャットボットを移植しアウトプットする」です。以前の宿題「LINEbot+API」に挑戦した際のコードに少し手を加えて、「いぬ」とリクエストすると犬の画像をレスポンスするLINEbotをherokuに乗せて公開します。

QR.png

'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: 'ここにはLINEbotのチャンネルシークレットを書く',
    channelAccessToken: 'ここにはLINEbotのチャンネルアクセストークンを書く'
};

const app = express();
let requetText='';

app.post('/webhook', line.middleware(config), (req, res) => {
    requetText=req.body.events[0].message.text;
    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);
  }

  let mes = 'ちょっとまってね'; // 待ってねってメッセージだけ先に処理

  getQiitaTag(event.source.userId , event.message.text); // スクレイピング処理が終わったらプッシュメッセージ

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

const getQiitaTag = async (userId,tag) => {
    let mes = '';
    try {
        if(requetText==="いぬ"){
        const res = await axios.get('https://random.dog/woof.json');
        const item = res.data.url;
        mes = item;
        }else if(requetText==="しばいぬ"){
        const res = await axios.get('http://shibe.online/api/shibes?count=1&urls=true&httpsUrls=true');
        const item = res.data[0];
        mes = item;
        }else{     
        mes = "いぬしかわかりません";
        }


    } catch (error) {
        // 該当しないものは404でエラーになる
        const {
            status,
            statusText
        } = error.response;
        console.log(`Error! HTTP Status: ${status} ${statusText}`);
        if( status == 404 ){
            mes = 'Qiitaのタグ「' + tag + '」の記事はありませんでした';
        } else {
            mes = `Error! HTTP Status: ${status} ${statusText}`;
        }
    }

    await client.pushMessage(userId, {
        type: 'text',
        text: mes,
    });
}

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

リクエストが「しばいぬ」だった場合には柴犬APIを呼んで柴犬画像をレスポンスするif文も入れてみました。

今回授業にて、ExpressにおいてHTTPSのpostリクエストを投げる際の処理を学んだことから、LINE上で何か打ち込まれた際それがwebhookに対するpost通信であるため、

app.post('/webhook', line.middleware(config), (req, res) => {
    requetText=req.body.events[0].message.text;
    Promise
      .all(req.body.events.map(handleEvent))
      .then((result) => res.json(result));
});

という関数が実行されるのだと気づきました。
一方で「Promise~」以降のコードが何を表しているのかサッパリなので、Promiseについて調べてみます。

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