駄文型

プログラミングとか英語とかの話題を中心にした至極ちゃらんぽらんな日記です。

Slackに天気予報を投稿するbot作ってみた(Ruby/Heroku)

photo by Kris Krug

Slackを使ってみたくて家庭用のチームを作って導入してみた。天気予報をSlackに流そうと思ってfeedを登録したりIFTTTから流すようにしたのだが、イマイチだったのでRubyの勉強がてら↓のエントリを参考にbotを作ってみた。

shoyan.github.io

出力サンプル

f:id:koheikimura:20160207130707p:plain

導入手順

ソースコードのダウンロード

git clone https://github.com/shoyan/slack-weather-notifier

Wether Hacksから地域IDの取得

そのままだと福岡の天気になるので、都市のIDをWeather Hacksの定義表から取得する。横浜(神奈川県東部)の場合は140010

ソースコードの編集

別にそのままでも良いのだが、勉強も兼ねてお天気Webサービス仕様 - Weather Hacks - livedoor 天気情報Attachments | Slackを参考にレイアウトを自分好みに変更してみた。地域を変更する場合はURLのcity=140010の部分を先ほど取得したIDに変更する。

require 'json'
require 'open-uri'
require 'slack/incoming/webhooks'

def post_to_slack text, attachments: attachments
  slack = Slack::Incoming::Webhooks.new ENV['WEBHOOK_URL']
  slack.post text, attachments: attachments
end

def temperature weather, maxmin
  temperature = weather['temperature'][maxmin]

  if temperature.nil?
    "---"
  else
    "#{temperature['celsius']}"
  end
end

def post_weather_for weather, link: link
  min     = temperature weather, 'min'
  max     = temperature weather, 'max'

  title   = "#{weather['dateLabel']}の天気 『#{weather['telop']}"
  text    = "最低気温 #{min}\n最高気温 #{max}\n#{weather['date']}"

  attachments = [{
    title: title,
    title_link: link,
    text: text,
    image_url: weather['image']['url'],
    color: "#7CD197"
  }]

  post_to_slack "", attachments: attachments
end

uri = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=140010'

res         = JSON.load(open(uri).read)
title       = res['title']
provider    = res['copyright']['provider'].first['name']
description = res['description']['text'].delete("\n")
link        = res['link']
today       = res['forecasts'][0]
tomorrow    = res['forecasts'][1]

attachments = [{
  title: title,
  title_link: link,
  text: provider
}]

post_to_slack description, attachments: attachments
post_weather_for today, link: link
post_weather_for tomorrow, link: link

Webhook URLの発行

https://<example>.slack.com/services/new/incoming-webhookにアクセスして通知先のチャンネルを選択後、Add Incoming Webhooks IntegrationをクリックすればWebhook URLが発行される。通知するbotの名称やアイコンも設定できる。アイコンは絵文字から選択することができるので便利。はじめは天気マークの絵文字を使っていたが、紛らわしいのでロボットマークに変更した。

Webhook URLを環境変数に設定

export WEBHOOK_URL="さっき取得したURL"

Gemのインストール

gem install slack-incoming-webhooks

Slackへの通知のテスト

上の2つを設定すれば実行できるはずなので、コンソールで

ruby slack-weather-notifier.rb

と実行すれば、チャンネルに天気予報が登録されるはず。レイアウト等を変更したい場合はここで実行しながら確認するといいかも。

Herokuへデプロイ

作成したbotをHerokuへデプロイする。

heroku login
heroku create
git init
git add .
git commit -m "first commit"
git push heroku master

環境変数の設定も忘れずに。

heroku config:set WEBHOOK_URL=ここにwebhook_urlを入力

スケジューラの設定

スケジューラの設定にはHerokuのアドオンが必要。アドオンを使用するにはクレジットカードの登録も必要なので、登録していない場合は登録する。

https://dashboard.heroku.com/account/billing

クレジットカード情報を登録したらスケジューラを追加し、管理画面を開く。

heroku addons:add scheduler:standard
heroku addons:open scheduler

ブラウザにスケジューラ管理画面が表示されるので、ruby slack-weather-notifier.rbを登録する。ただし時刻はUTCなので、日本時間マイナス9時間で設定する。僕は毎日朝7時と昼の12時、夜の21時に通知されるようにした。

f:id:koheikimura:20160207135912p:plain

これで完了。あとはスケジュールどおり実行されることを祈るのみ。

ソースコード

github.com

感想

  • Ruby初心者なので基本的な構文でかなりつまずいた。
    • その度にググったりリファレンスを見たりすることに。
    • elseifと書いて動かないとか。
  • Ruby的な書き方もわからない。
  • 最近写経するような勉強ばかりだったので楽しかった。
  • 電車遅延情報もいいFeedがないのでいい感じにしたい。

あわせてどうぞ