Skip to content

Instantly share code, notes, and snippets.

@kakijin
Created September 4, 2016 05:50
Show Gist options
  • Select an option

  • Save kakijin/cdd0e8ac8fd1e7833e2cb2908182630c to your computer and use it in GitHub Desktop.

Select an option

Save kakijin/cdd0e8ac8fd1e7833e2cb2908182630c to your computer and use it in GitHub Desktop.

Revisions

  1. kakijin created this gist Sep 4, 2016.
    72 changes: 72 additions & 0 deletions google-api-calender.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    # 参考URLもといコピー元
    # https://developers.google.com/google-apps/calendar/quickstart/ruby?hl=ja

    require 'google/apis/calendar_v3'
    require 'googleauth'
    require 'googleauth/stores/file_token_store'

    require 'fileutils'

    OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
    APPLICATION_NAME = 'Retty Hackathon Chat Bot Program'
    # OAuth 認証用のclient IDはその他で作成すること
    CLIENT_SECRETS_PATH = 'client_secret_etc.json'
    # OAuth 認証したユーザの情報をcalendar-ruby.jsonに保存
    CREDENTIALS_PATH = 'calendar-ruby.json'
    # 読み込み権限のみのカレンダーAPIを指定
    SCOPE = Google::Apis::CalendarV3::AUTH_CALENDAR_READONLY
    module GoogleApi
    def authorize
    FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))

    client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
    token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
    authorizer = Google::Auth::UserAuthorizer.new(
    client_id, SCOPE, token_store
    )
    user_id = 'default'
    credentials = authorizer.get_credentials(user_id)

    if credentials.nil?
    url = authorizer.get_authorization_url(
    base_url: OOB_URI
    )
    puts url

    code = gets
    credentials = authorizer.get_and_store_credentials_from_code(
    user_id: user_id,
    code: code,
    base_url: OOB_URI
    )

    end
    credentials
    end

    def initialize_api
    # Initialize the API
    service = Google::Apis::CalendarV3::CalendarService.new
    service.client_options.application_name = APPLICATION_NAME
    service.authorization = authorize
    return service
    end

    def fetch_calender(service, max_results = 10, order_by = 'startTime')
    calendar_id = 'primary'
    response = service.list_events(
    calendar_id,
    max_results: max_results,
    single_events: true,
    order_by: order_by,
    time_min: Time.now.iso8601
    )

    if response.items.empty?
    response = "イベントが見つかりませんでした。"
    else
    response
    end
    end
    end