概要
今日は風が強かったので
強風時に「今日は風が騒がしいな・・」って返してくれるLINEのBOTを作ってみた。
風速はyahoo apiから取得。
通知先は最近Line bot apiが使えるようになったで試してみる。
サーバーはherokuを使用。(今回はあまり触れません。)
環境
heroku + node6.0 + es6 + express4.13
準備
LINEアカウント設定
LINEのアカウントは、 https://developers.line.me で取得
channelsからそれぞれの値を取得して
.env
に保存LineのCallback URLを設定
httpsでポート番号443を指定しないとダメっぽい
(https://hogehoge.com:443/callback
的な)
固定IP
- APIの呼び出し元のIPアドレスをLINEのServer IP Whitelistに設定
今回はherokuで動かしたのでherokuのaddonFixie
を使用
とりあえず動くもの
.env
LINE_CHANNEL_ID=<<Channel ID>>
LINE_CHANNEL_SECRET=<<Channel Secret>>
LINE_CHANNEL_MID=<<MID>>
FIXIE_URL=<<FIX_URL>> // Fixie使う場合
app.js
const express = require('express')
const app = express()
const rp = require('request-promise')
const bodyParser = require('body-parser')
require('dotenv').config({silent: true})
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
const getWind = place =>
rp.get({
url: 'https://query.yahooapis.com/v1/public/yql',
headers: {
'Content-Type': 'application/json; charset=UTF-8'
},
json: true,
qs: {
format: 'json',
env: 'store://datatables.org/alltableswithkeys',
q: `select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="${place}")`
}
})
.then(result => !result.error ? Promise.resolve(result.query.results.channel.wind) : Promise.reject('can not get wind'))
const lineSendMessage = (to, text) =>
rp.post({
url: 'https://trialbot-api.line.me/v1/events',
proxy: process.env.FIXIE_URL, // proxy使わないならいらない
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'X-Line-ChannelID': process.env.LINE_CHANNEL_ID,
'X-Line-ChannelSecret': process.env.LINE_CHANNEL_SECRET,
'X-Line-Trusted-User-With-ACL': process.env.LINE_MID
},
json: true,
body: {
to: to,
toChannel: 1383378250, // Fixed value
eventType: '138311608800106203', // Fixed value
content: {
toType: 1,
contentType: 1,
text: text
}
}
})
app.post('/callback', (req, res) =>
getWind('tokyo') // とりあえず東京固定
.then(wind => {
// 34ノットあたりから強風と呼べるぽい
if (+wind.speed > 34) {
lineSendMessage([req.body.result[0].content.from], '今日は風が騒がしいな・・')
}
res.send(wind)
})
)
app.listen(process.env.PORT || 3000)
callback時に発言者のMIDが取れるので、宛先MIDを固定で毎日cronで回すのも良。
参考リンク
Yahoo Weather API
LINE bot API
気象庁