LoginSignup
10
6

More than 3 years have passed since last update.

【LINE BOT】WebAPIを使用し自動返信BOTを作ってみた

Last updated at Posted at 2020-09-01

はじめに

LINE BOTを利用し、六曜日とその内容を自動で返信するものを作りをました。
入力文字を替えることで、NASA(非公式)の「今日の天文学写真」を楽しむこともできます。

目的

六曜にこだわる人は少なくなってきていると思いますが、まだ大安などの吉日を好む人は多いと思います、個人的なイベントが発生すると「今日は大安だっけ?」「友引かな?」などとたまに気にすることがあるので、「今日は」と入力する今日の六曜日を自動返信するBOTを製作しました。

別で作ったほうがいいかと思いましたが、今回は練習も兼ねてで画像も取得したいと思いましたので、「今日の画像は」と入力するとNASA(非公式)より「今日の天文学写真」を取得し自動で表示します。宇宙の美しさ広さをみて、自分の小ささを感じます。

作ったもの

Image from Gyazo

構成

環境

  • node.js v14.5.0
  • @line/bot-sdk 7.0.0
  • axios 0.19.2
  • date-utils 1.2.21
  • express 4.17.1

LINE Messaging API

Node.jsでLINE BOTを作る方法はこちらを参考にしました。

1時間でLINE BOTを作るハンズオン (資料+レポート) in Node学園祭2017 #nodefest

今回使用したWEBAPI

コード

server.js
"use strict";

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

const config = {
    channelSecret: 'channelSecret',
    channelAccessToken: 'channelAccessToken'
};

const app = express();
require('date-utils');

var dt = new Date();
var formatted = dt.toFormat("YYYY-MM-DD");
console.log(formatted);

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'|| event.message.type !== 'location') {
        return Promise.resolve(null);
    }



    let shakkou='';
   let mes = '';
    if(event.message.text === '今日は') {//「きょうは」と入力する。
    const res = await axios.get('https://dateinfoapi.appspot.com/v1?date='+ formatted);
    const pushText = res.data.rokuyo;
        if(res.data.rokuyo === '赤口'){
            shakkou ="正午の前後を除いて凶日、午前11時ごろから午後1時ごろまでは吉です。";
        }else if(res.data.rokuyo === '大安'){
            shakkou ="何事においても吉、成功しないことはない日";
        }else if(res.data.rokuyo === '先勝'){
            shakkou ="午前は吉、午後は凶";
        }else if(res.data.rokuyo === '友引'){
            shakkou ="朝晩は吉、昼は凶";
        }else if(res.data.rokuyo === '先負'){
            shakkou ="午前は凶、午後吉";
        }else if(res.data.rokuyo === '仏滅'){
            shakkou ="大凶日";
        }
    console.log(pushText);
    mes = '今日は「'+ pushText +'」です。\n'+ shakkou;
    return client.replyMessage(event.replyToken, {
        type: 'text',
        text: mes,
    });
    }else if(event.message.text === '今日の画像は'){
        const response = await axios.get('https://api.nasa.gov/planetary/apod?api_key='+ {APIkey});
        console.log(response.data.url);
    await client.pushMessage(event.source.userId, {
        type: 'image',
        originalContentUrl:response.data.url,
        previewImageUrl:response.data.url,
    }); 
    }
}



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

終わりに

LINEの国内ユーザー数は8400万人であり、SNSの中ではダントツで1位である、ちなみに2位のTwitterは4500万人(2020年6月時点)。メッセージインフラとして定着しているという利点があり。UIなども簡単にできるようなので、サービスを高速で構築できそう。

今後もLINE Messaging APIを活用しアウトプットしたいと思います。

10
6
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
10
6