Mae向きなブログ

Mae向きな情報発信を続けていきたいと思います。

Googleカレンダーに予定をRubyで登録する

Googleカレンダー、非常に便利で、仕事やプライベートの予定を入力して、自宅のMac、職場のWindows PC、iPhoneiPadで便利に活用しています。
いつもは仕事の予定を1つずつWebから入力していたのですが、google-api-clientというgemを使うとRubyから登録できそうということで取り組んでみました。
gemのインストールからスクリプトを実行する前までの設定については参考サイトが有益だと思います。

my_calendar.rb

#!/usr/bin/env ruby
# coding: utf-8
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/file_storage'
require 'date'

CLINET_SECRET = 'client_secret.json' # ダウンロードしたjsonファイル
CALENDAR_ID   = 'ここにcalendarIDを記入'

client = Google::APIClient.new(:application_name => '')

# 認証
authfile = Google::APIClient::FileStorage.new('.authfile')
unless authfile.authorization.nil?
  client.authorization = authfile.authorization
else
  client_secrets = Google::APIClient::ClientSecrets.load(CLINET_SECRET)

  flow = Google::APIClient::InstalledAppFlow.new(
    :client_id => client_secrets.client_id,
    :client_secret => client_secrets.client_secret,
    :scope => ['https://www.googleapis.com/auth/calendar']
  )
  client.authorization = flow.authorize(authfile)
end

# イベント取得
cal = client.discovered_api('calendar', 'v3')

start_date = '2014-12-28'
end_date = (Date.parse('2014-12-30')+1).to_s

event = {
  'summary' => 'GoogleAPIから挿入できた!',
  'start' => {
    'date' => '2014-12-28',
  },
  'end' => {
    'date' => "#{end_date}",
  }
}

result = client.execute(:api_method => cal.events.insert,
                        :parameters => {'calendarId' => CALENDAR_ID},
                        :body => JSON.dump(event),
                        :headers => {'Content-Type' => 'application/json'})

p result.status

注意点

  • その1

簡単なサンプルを作って実行したのですが、以下のようなエラーが出力されました。

google-api-client-0.7.1/lib/google/api_client.rb:595:in `execute!': unknown keyword: interval (ArgumentError)

これは、以下のように対処することで解決しました。

$ gem uninstall retriable
$ gem install retriable --version '1.4.1' --no-ri --no-rdoc
  • その2

例えば、12/28〜12/30までの予定を登録するとき、end_dateに'2014-12-30'を設定すると、Googleカレンダーには12/28〜12/29までの予定として登録されました。そこで、以下のように日付+1するようにしました。

end_date = (Date.parse('2014-12-30')+1).to_s

実行結果