Skip to content

Instantly share code, notes, and snippets.

@howtodowtle
Last active February 11, 2022 08:12
Show Gist options
  • Save howtodowtle/bd057d476fe3af0757c4c9e0950e8fc3 to your computer and use it in GitHub Desktop.
Save howtodowtle/bd057d476fe3af0757c4c9e0950e8fc3 to your computer and use it in GitHub Desktop.
Send Oura bedtime to Beeminder as "hours before midnight"
#! /usr/bin/ruby
# frozen_string_literal: true
# Original script: Bee from beeminder --> https://forum.beeminder.com/t/oura-integration/9592
# A script to fetch my bedtime from Oura and update my beeminder goal
# If run with no arguments it fetches the last 5 days from Oura. Does not update existing datapoints.
require 'httparty'
OURA_TOKEN = 'YOUR_OURA_PERSONAL_ACCESS_TOKEN'
OURA_API = 'https://api.ouraring.com/v1/'
BEEMINDER_TOKEN = 'YOUR_BEEMINDER_PERSONAL_ACCESS_TOKEN'
BEEMINDER_USERNAME = 'YOUR_BEEMINDER_USERNAME'
BEEMINDER_API = 'https://www.beeminder.com/api/v1/'
BEEMINDER_GOAL = 'YOUR_BEEMINDER_GOAL'
DAYS_TO_FETCH = 5
SECONDS_PER_DAY = 24 * 60 * 60
VERSION = '0.2'
stepurl = "#{BEEMINDER_API}users/#{BEEMINDER_USERNAME}/goals/#{BEEMINDER_GOAL}"
now = Time.now
params = {
start: (now - SECONDS_PER_DAY * DAYS_TO_FETCH).strftime('%F'),
end: now.strftime('%F')
}
headers = { "Authorization": "Bearer #{OURA_TOKEN}" }
# activity = HTTParty.get(OURA_API+"activity", headers: headers, query: params).parsed_response["activity"]
sleep = HTTParty.get("#{OURA_API}sleep", headers: headers, query: params).parsed_response['sleep']
# transform the data into date,value pairs
sleep.map! do |act|
[Date.parse(act['summary_date']), act['bedtime_start_delta']]
end
data = HTTParty.get("#{stepurl}/datapoints.json",
query: { auth_token: BEEMINDER_TOKEN, count: 6, sort: 'daystamp' }).parsed_response
# check if Beeminder has an existing datapoint before adding our data
sleep.each do |date, bedtime_start_delta|
date += 1 # count sleep for the day after wakeup
datapt = data.select { |dat| dat['daystamp'] == date.strftime('%Y%m%d') }.first
if datapt.nil?
# add a datapoint
HTTParty.post("#{stepurl}/datapoints.json", body: {
auth_token: BEEMINDER_TOKEN,
value: -bedtime_start_delta.to_f / 60 / 60, # convert to hours before midnight, make float
daystamp: date.strftime('%Y%m%d'),
comment: "From Oura. Entered at #{Time.now.iso8601} using version #{VERSION}."
})
# # update a datapoint
# elsif datapt && datapt['value'] < bedtime_start_delta
# # ok, but there is a datapoint and it has less steps than oura
# HTTParty.put(stepurl + "/datapoints/#{datapt['id']}.json", body: {
# auth_token: BEEMINDER_TOKEN,
# value: bedtime_start_delta,
# daystamp: date.strftime('%Y%m%d'),
# comment: "#{datapt['comment']}; Up:#{Time.now.strftime('%H:%M')}"
# })
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment