Skip to content

Instantly share code, notes, and snippets.

@vivahiraj
Last active January 1, 2016 07:49
Show Gist options
  • Save vivahiraj/8114172 to your computer and use it in GitHub Desktop.
Save vivahiraj/8114172 to your computer and use it in GitHub Desktop.
rubyでGoogle Calendarをいじるサンプルです。 仕事用カレンダーを取得して、今日から31日以内のイベントを削除して二つイベントを追加します。 事前にGoogle Developers Consoleにアプリケーションを登録してClient IDとClient secretを取得して google-api oauth-2-login --scope=https://www.googleapis.com/auth/calendar --client-id=CLIENT_ID --client-secret=CLIENT_SECRET を行って.google-api.yamlを作成する必要があります。
# -*- 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'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment