Skip to content

Instantly share code, notes, and snippets.

@eiiot
Last active January 9, 2023 22:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eiiot/0603add6cbfd967a000b3db1799f4a3e to your computer and use it in GitHub Desktop.
Save eiiot/0603add6cbfd967a000b3db1799f4a3e to your computer and use it in GitHub Desktop.
Hourly Rain in Google Calendar
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
function updateCalendar() {
let response = UrlFetchApp.fetch('https://api.openweathermap.org/data/2.5/onecall?lat={{YOUR LATITUTE HERE}}&lon={{YOUR LONGITUDE HERE}}&units=imperial&appid={{YOUR API KEY HERE}}')
let weather = JSON.parse(response.getContentText());
let hourly = weather.hourly;
// loop through hourly weather for the next day. If rain is expected, then find when it stops.
let currentHourStart;
let duration = 0;
// delete all events in the calendar
let rainCalendar = CalendarApp.getCalendarById('{{YOUR GOOGLE CALENDAR ID HERE}}');
let before = new Date().addHours(-24);
let after = new Date().addHours(48);
let events = rainCalendar.getEvents(before, after);
events.forEach(event => {
console.log('Deleting:', event.getTitle());
event.deleteEvent();
})
hourly.forEach(hour => {
if (hour.pop > 0.3) {
if (currentHourStart) {
console.log("Rain continuing at ", new Date(+hour.dt * 1000));
duration += 1;
} else { // there is no current start hour
console.log("Rain starting at ", new Date(+hour.dt * 1000));
currentHourStart = hour.dt;
duration += 1;
}
} else {
if (currentHourStart) {
// push to gcal
console.log("Rain ending at ", new Date(+hour.dt * 1000));
let startTime = new Date(+currentHourStart * 1000);
let endTime = new Date(+currentHourStart * 1000).addHours(duration);
rainCalendar.createEvent('Precipitation 🌧️', startTime, endTime);
currentHourStart = null;
duration = 0;
}
}
})
// check if the rain never stopped :)
if (currentHourStart) {
// push to gcal
console.log("Rain ending at ", new Date(+hour.dt * 1000));
let startTime = new Date(+currentHourStart * 1000);
let endTime = new Date(+currentHourStart * 1000).addHours(duration);
rainCalendar.createEvent('Precipitation 🌧️', startTime, endTime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment