LoginSignup
4
5

More than 5 years have passed since last update.

Node.jsで特定の電車遅延情報をLINEに送信する

Last updated at Posted at 2018-07-07

環境

  • Node.js(v8.10.0)

必要なパッケージのインストール

下記のパッケージをインストールします。

  • axios(v0.16.2)
  • querystring(v0.2.0)
DOS
npm install axios
npm install querystring

遅延情報をJSONで取得するモジュール

遅延情報はこちらのAPIを使用させて頂きました。
鉄道遅延情報のjson

deley.js
let https = require('https');
const URL = 'https://rti-giken.jp/fhc/api/train_tetsudo/delay.json';

const Deley = function () {};

Deley.prototype.getDeleyData = function () {
    return new Promise(function (resolve) {
        https.get(URL, (res) => {
            let body = '';
            res.setEncoding('utf8');

            res.on('data', (chunk) => {
                body += chunk;
            });

            res.on('end', (res) => {
                res = JSON.parse(body);
                resolve(res);
            });
        }).on('error', (e) => {
            console.log(e.message);
        });
    });
};

module.exports = Deley;

httpモジュールもhttpsモジュールもgetメソッドが非同期なので、単純に呼び出しても大変扱いにくいという・・・
そんな時にPromiseが役に立つということで、こんな感じにしてみました。
下のLINEモジュールはaxiosを使用していますが、こっちはaxiosを使わずに生Promiseで書いています。

LINEに投稿するモジュール

line.js
const axios = require('axios');
const querystring = require('querystring');

const Line = function () {};

Line.prototype.setToken = function (token) {
    this.token = token;
};

Line.prototype.notify = function (text) {
    // トークンチェック
    if (this.token == undefined || this.token == null) {
        return;
    }
    // 投稿
    axios({
            method: 'post',
            url: 'https://notify-api.line.me/api/notify',
            headers: {
                Authorization: `Bearer ${this.token}`,
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            // リクエストデータの生成にquerystringを使用
            data: querystring.stringify({
                message: text,
            }),
        })
        .then(function (res) {
            console.log(res.data);
        })
        .catch(function (error) {
            console.error(error);
        });
};

module.exports = Line;

投稿してみる

実際に投稿するには【公式】LINE Notifyでトークンを発行する必要があります。
発行したトークンはsetToken()の引数に渡してください。

index.js
const Line = require('./line');
const Deley = require('./deley');

const myLine = new Line();
const myDeley = new Deley();

// LINE Notify トークンセット
myLine.setToken("トークン文字列");

// 遅延情報を取得
myDeley.getDeleyData().then(function(res){
    res.forEach(function(data){
       // LINE Notify 実行
       if(data.name == "東海道線" || data.name == "上野東京ライン"){
           myLine.notify("現在、" + data.name + "が遅延しています。");
       }
    });
});

今回は僕がよく使う東海道線と上野東京ラインの遅延情報だけを通知しています。
(コーディングした日はどちらの線も実際に15分程度遅延が起きていました。)

linenotify.png

HerokuにデプロイしてIFTTTとかで朝7:00、夕方18:00とかにAPI叩けば急な電車遅延にも対応できる!?

参考

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