経産省ニュースリリースをSlackに投げる

グレーゾーン解消制度における照会への回答を閲覧するため等、経済産業省ニュースリリースは重宝しているのですが、RSSフィードが用意されておらず、いちいち見に行かないといけないというのは結構面倒です。
というわけで、スクレイピングしてSlackのRSSチャンネルにニュースリリースを流すことにしました。なお、利用規約にもスクレイピングに関しては記載がなく、robots.txtも設置されていないので、(節度ある)スクレイピングは禁止されていません。

Gemfile

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

gem "slack-api"
gem "dotenv"
gem 'activerecord'
gem 'pg'
gem 'faraday'
gem "nokogiri"

config/env.rb

require 'dotenv'

Dotenv.load

config/active_record.rb

require 'active_record'
require_relative './env'

ActiveRecord::Base.establish_connection(
  adapter: 'postgresql',
  host: '',
  username: ENV['DB_USERNAME'],
  password: ENV['DB_PASSWORD'],
  database: ENV['DB_NAME']
)

class Meti < ActiveRecord::Base
end

config/slack.rb

require 'slack'
require_relative './env'

TOKEN = ENV['SLACK_RSS_TOKEN']
Slack.configure {|config| config.token = TOKEN}

./meti.rb

require 'faraday'
require 'nokogiri'
require './config/active_record'
require './config/slack'

uri = %(https://www.meti.go.jp/press/index.html)

Nokogiri::HTML(Faraday.get(uri).body).xpath('//a[@class="cut_txt"]').reverse_each do |node|
  hash = {
    uri: %(https://www.meti.go.jp#{node[:href]}),
    title: node.text
  }
  unless Meti.where(uri: hash[:uri]).reload.exists?
    Slack.chat_postMessage(
      channel: "rss",
      username: "経済産業省ニュースリリース",
      text: "<#{hash[:uri]}|#{hash[:title]}>",
      unfurl_links: 'true'
    )

    Meti.create(
      uri: %(#{hash[:uri]})
    )
  end
end

if Meti.all.reload.size > 20
  min_id = Meti.where(id: Meti.minimum(:id)).map(&:id)[0]
  max_id = Meti.where(id: Meti.maximum(:id)).map(&:id)[0]
  Meti.where(id: min_id..max_id-20).delete_all
end