2013-12-24

rubyでGoogle Calendarをいじる

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク
rubyでgoogleカレンダーをいじってみました。

コマンドラインからgoogleカレンダーをいじります。

google-api-clientを利用します。
なので
gem install google-api-client -v 0.6.4
gem install jwt -v 0.1.5
でインストールしておきます。
(※ここで記載している内容は0.6.4でないと動きません。またjwtも0.1.5より新しいのが入っていると動きません)

まずはGoogle Developers Consoleにプロジェクトを登録します。
登録したら「APIs & auth」の「APIs」で
Calendar API
を「ON」にします。

そして「APIs & auth」の「Credentials」でOAuth用のCLIENT IDを発行します。
「CREATE NEW CLIENT ID」でApplication typeを「Installed application」、Installed application typeを「Other」としてCLIENT IDを作成して、作成されたCLIENT IDとCLIENT SECRETを控えます。
(※ここいら辺も変更されていますが、似たような設定はできる感じです)

google-api-clientをインストールしたらgoogle-apiをいうコマンドが利用できるようになっているので、これを利用して一度OAuth認証を行います。
以下のような感じです。CLIENT_IDとCLIENT_SECRETは控えたもので置き換えてください。

google-api oauth-2-login --scope=https://www.googleapis.com/auth/calendar --client-id=CLIENT_ID --client-secret=CLIENT_SECRET

コマンドを実行するとwindows環境であればブラウザが開いてOAuthの許可を求められるので許可します。認証が完了するとホームディレクトリ(Windows7の場合は、C:\Users\mynameみたいなところの下)に.google-api.yamlが作成されるので、今回作成するプログラムを置く場所に移動しておきます。

このyamlファイルにOAuthでの認証情報が保存されているようなので、この情報を利用します。
でgoogleカレンダーをいじるrubyスクリプトは以下のような感じです。
カレンダー一覧から「仕事用」カレンダーを選び、今日から31日に以内のイベントをすべて削除して、イベントを二つ追加しています。

# -*- encoding: utf-8 -*-
require 'rubygems'
require 'yaml'
require 'date'
require "google/api_client"
oauth_yaml = YAML.load_file('.google-api.yaml')
client = Google::APIClient.new({:application_name => "gcalxx",:application_version => "1.0"})
client.authorization.client_id = oauth_yaml["client_id"]
client.authorization.client_secret = oauth_yaml["client_secret"]
client.authorization.scope = oauth_yaml["scope"]
client.authorization.refresh_token = oauth_yaml["refresh_token"]
client.authorization.access_token = oauth_yaml["access_token"]
if client.authorization.refresh_token && client.authorization.expired?
client.authorization.fetch_access_token!
end
service = client.discovered_api('calendar', 'v3')
#カレンダーリストの取得
gcal_list = client.execute(:api_method => service.calendar_list.list)
gcal_id = nil
gcal_list.data.items.each do |c|
if c["summary"] == "仕事用"
gcal_id = c["id"]
break
end
end
logexit("cant find calendar") if gcal_id.nil?
#googleカレンダー既存情報削除
today = Date.today
today31 = Date.today + 31
params = {}
params['calendarId'] = gcal_id
params['timeMin'] = Time.utc(today.year, today.month, today.day, 0).iso8601
params['timeMax'] = Time.utc(today31.year, today31.month, today31.day,0).iso8601
events = client.execute(:api_method => service.events.list,:parameters => params)
while true
events.data.items.each do |e|
client.execute(:api_method => service.events.delete,
:parameters => {'calendarId' => gcal_id, 'eventId' => e["id"]})
end
if !(page_token = events.data.next_page_token)
break
end
params["pageToken"] = page_token
events = client.execute(:api_method => service.events.list,:parameters => params)
end
#googleカレンダーへの登録
event = {}
event["summary"] = "お試しall dayイベント"
event["start"] = {"date" => today.strftime("%Y-%m-%d")}
event["end"] = {"date" => today.strftime("%Y-%m-%d")}
client.execute(:api_method => service.events.insert,
:parameters => {'calendarId' => gcal_id},
:body => JSON.dump(event),
:headers => {'Content-Type' => 'application/json'})
event2 = {}
event2["summary"] = "お試しイベント"
event2["start"] = {"dateTime" => Time.now.iso8601}
event2["end"] = {"dateTime" => (Time.now + 3600).iso8601}
client.execute(:api_method => service.events.insert,
:parameters => {'calendarId' => gcal_id},
:body => JSON.dump(event2),
:headers => {'Content-Type' => 'application/json'})
view raw gcalxx.rb hosted with ❤ by GitHub

以下を参考にさせていただきました。
http://blogaomu.com/2012/09/16/ruby-script-using-google-calendar-api

0 件のコメント: