Google Analytics API を使って前日の PV をツイートするコードを Ruby で書いてみた
よく読んでいる日記を見て、同じような仕組みを作ってみようと思い、 Ruby で書いてみました。
- Google Analytics API を使って前日の PV を取得するコードを C# で書いてみた - しばやん雑記
Google アナリティクスの情報を、 Google Developer Consoles を介して取得します。
ざっくりと書いたので例によってメソッド化とかエラー処理とかないです。
debian 7.8 上の Ruby 2.2 系で書き、 cron で動作させます。
毎日0時6分くらいに前日の PV をツイートするはずです。
Ruby で Google Developer Consoles を扱うに当たって Rubygems をインストールします。
Google Developer Consoles のために google-api-clinet
を、 結果をツイートするために twitter
を、JSON で保存した設定を取り出すために json
を入れておきます。
$ gem install google-api-client $ gem install twitter $ gem install json
サンプルが google-api-ruby-client-samples/service_account にあるのでそこから必要そうな部分をもらってきます。
前日の日付と PV を visitCount にセットしてから twitter
に CS/CK と AT/ATS を突っ込んでツイートさせました。
#!/usr/bin/env ruby # coding: utf-8 require 'rubygems' require 'json' require 'google/api_client' require 'date' require 'twitter' config = open('~/.google/config.json') do |io| JSON.load(io) end service_account_email = config['service_account_email'] key_file = config['key_file'] key_secret = config['key_secret'] profile_id = config['profile_id'] client = Google::APIClient.new(:application_name => 'Get-AccessCount') key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret) client.authorization = Signet::OAuth2::Client.new( :token_credential_uri => 'https://accounts.google.com/o/oauth2/token', :audience => 'https://accounts.google.com/o/oauth2/token', :scope => 'https://www.googleapis.com/auth/analytics.readonly', :issuer => service_account_email, :signing_key => key ) client.authorization.fetch_access_token! analytics = client.discovered_api('analytics','v3') startDate = (DateTime.now - 1).strftime("%Y-%m-%d") endDate = startDate visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => { 'ids' => "ga:" + profile_id, 'start-date' => startDate, 'end-date' => endDate, 'dimensions' => "ga:day,ga:month", 'metrics' => "ga:visits", 'sort' => "ga:month,ga:day" }) tweet_string = "昨日の えぢた2.2 の PV は #{visitCount.data.rows[0][2]} でした\nhttp://k-side.hatenablog.jp/ " twitter_client = Twitter::REST::Client.new do |twconfig| twconfig.consumer_key = config['consumer_key'] twconfig.consumer_secret = config['consumer_secret'] twconfig.access_token = config['access_token'] twconfig.access_token_secret = config['access_token_secret'] end twitter_client.update(tweet_string) exit 0
設定ファイルはキーファイルやパスワード、 Twitter の トークンなどを含んでいるので 、ホームディレクトリに .google
ディレクトリを作り、そこに下記のような config.json
を保存。パーミッションを変更しておきました。
{ "service_account_email" : "******@developer.gserviceaccount.com", "key_file" : "******.p12", "key_secret" : "******", "profile_id" : "******", "consumer_key" : "******", "consumer_secret" :"*****", "access_token" : "******", "access_token_secret" : "******" }