Ruby で Google カレンダ取得
# Initialize the client & Google+ API
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'json'
require "yaml"
require "time"
# Initialize OAuth 2.0 client
# authorization
# client = Google::APIClient.new(
# :application_name => 'Rails Calendar',
# :application_version => '1.0.0'
# )
# 認証部分(取得できていれば不要)
# plus = client.discovered_api('plus')
#
# Google Console でアプリを作る必要がある
# flow = Google::APIClient::InstalledAppFlow.new(
# :client_id => 'ここにクライアントID',
# :client_secret => 'ここにクライアントシークレットID',
# :scope => ['https://www.googleapis.com/auth/calendar']
# )
#
# # 認証開始
# client.authorization = flow.authorize
#
# # 認証情報をファイルへ書き込む
# File.open("./.google-api.yaml", "w"){|f|
# x = {
# "mechanism" => "oauth_2",
# "scope" => "https://www.googleapis.com/auth/calendar",
# "client_id" => client.authorization.client_id,
# "client_secret" => client.authorization.client_secret,
# "access_token" => client.authorization.access_token,
# "refresh_token" => client.authorization.refresh_token
# }
# f.puts(x.to_yaml)
# }
# ファイルを読み込む
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
# カレンダー API のインスタンス化
cal = client.discovered_api('calendar', 'v3')
# カレンダーリストの取得
page_token = nil
result = client.execute(:api_method => cal.calendar_list.list)
while true
entries = result.data.items
entries.each do |e|
print e.summary + "\n"
end
if !(page_token = result.data.next_page_token)
break
end
result = client.execute(:api_method => service.calendar_list.list,
:parameters => {'pageToken' => page_token})
end
p result.data.items
# # イベント取得月の確認
# printf("カレンダーを表示する年(20XX):")
# year = gets.strip.to_i
# printf("カレンダーを表示する月(1-12):")
# month = gets.strip.to_i
today = Date.today
today31 = Date.today + 31
# 時間を格納
time_min = Time.utc(today.year, today.month, today.day, 0).iso8601
time_max = Time.utc(today31.year, today31.month, today31.day,0).iso8601
# イベントの取得
params = {'calendarId' => 'primary',
'orderBy' => 'startTime',
'timeMax' => time_max,
'timeMin' => time_min,
'singleEvents' => 'True'}
# データの取得(取得方法は Google のサイトを参考にする)
result = client.execute(:api_method => cal.events.list,
:parameters => params)
# イベントの格納
events = []
result.data.items.each do |item|
events << item
end
# 出力
events.each do |event|
printf("%s,%s\n",event.start.dateTime, event.summary)
end