何かやってみるブログ

興味をもったこと、趣味のこと、技術について色々書きます。

Oura Ring API V2で軽く遊んだ時のメモ

概要

人差し指につけているOura RingのAPIの存在があることを知ってから遊んでみたかったもの新しくアプリを作るのは面倒だったので、既存のRuby on Jetsで作成したbotアプリを拡張してAPIを叩いて遊んでみた時のメモです。

やったこと

とりあえず詳細をSlack通知させる。

class OuraringJob < ApplicationJob
  cron '0 2 * * ? *'
  def sleep_result_notify
    url = URI('https://api.ouraring.com/v2/usercollection/sleep')
    start_date = Date.yesterday.to_s
    end_date = Date.tomorrow.to_s
    today = Date.today.to_s
    url.query = URI.encode_www_form({ start_date: start_date, end_date: end_date })
    response = HTTParty.get(url, { headers: { 'Authorization': "Bearer #{ENV["OURA_RING_TOKEN"]}" } })
    body = JSON.parse(response.body)
    target_hash = body['data'].find { |data| data['day'] == today }
    if target_hash.nil?
      send_message("データがありませんでした")
      return
    end

    deep_sleep_time = target_hash["deep_sleep_duration"] ? Time.at(target_hash['deep_sleep_duration']).utc.strftime('%X') : 'データがありませんでした'
    rem_sleep_time = target_hash['rem_sleep_duration'] ? Time.at(target_hash["rem_sleep_duration"]).utc.strftime('%X') : 'データがありませんでした'

    ## メッセージを作成する
    text = <<~"STR"
      今日の睡眠の結果です。
      > 睡眠開始時刻: #{Time.parse(target_hash["bedtime_start"]).to_s}
      > 睡眠終了時刻: #{Time.parse(target_hash["bedtime_end"]).to_s}
      > 深い睡眠時間: #{deep_sleep_time}
      > レム睡眠時間: #{rem_sleep_time}
      > 睡眠効率: #{target_hash["efficiency"]}
    STR
    # slackに送信する
    send_message(text)
  rescue StandardError => e
    send_message(e.backtrace)
  end
end

睡眠時間をGoogle Calendarにイベントとして登録する。

class OuraringJob < ApplicationJob
  cron '0 2 15 * ? *'
  def create_calendar_event
    url = URI('https://api.ouraring.com/v2/usercollection/sleep')
    start_date = Date.yesterday.to_s
    end_date = Date.tomorrow.to_s
    today = Date.today.to_s
    url.query = URI.encode_www_form({ start_date: start_date, end_date: end_date })
    response = HTTParty.get(url, { headers: { 'Authorization': "Bearer #{ENV["OURA_RING_TOKEN"]}" } })
    body = JSON.parse(response.body)
    target_hash = body['data'].find { |data| data['day'] == today }
    return if target_hash.nil?

    scope = %w(
      https://www.googleapis.com/auth/calendar
    )
    authorizer = Google::Auth::ServiceAccountCredentials.from_env(scope: scope)
    calendar = Google::Apis::CalendarV3::CalendarService.new
    calendar.authorization = authorizer

    event = Google::Apis::CalendarV3::Event.new(
      summary: '睡眠',
      start: Google::Apis::CalendarV3::EventDateTime.new(
        date_time: target_hash['bedtime_start'],
        time_zone: 'Asia/Tokyo'
      ),
      end: Google::Apis::CalendarV3::EventDateTime.new(
        date_time: target_hash['bedtime_end'],
        time_zone: 'Asia/Tokyo'
      )
    )

    calendar.insert_event(ENV['OURA_GOOGLE_CALENDAR_ID'], event, send_notifications: false)
    send_message('create calendar event')
  end
end