Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
office door
blinkt; sys_platform == "linux"
google-api-python-client
google-auth-httplib2
google-auth-oauthlib
python-dateutil
from datetime import datetime
import os.path
import pickle
import time
try:
import blinkt
blinkt_present = True
except:
blinkt_present = False
from dateutil import parser
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
if blinkt_present:
blinkt.set_clear_on_exit(True)
# If modifying these scopes, delete the file token.pickle
SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]
CALENDAR_ID = "" # ID of the calendar to use
COLOURS = {"BUSY": (255, 0, 0), "FREE": (0, 255, 0)}
QUERY_DELAY = 10 # Time in seconds to delay between querying the Google Calendar API
MAX_EVENTS_PER_CAL = 5
credentials = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists("token.pickle"):
with open("token.pickle", "rb") as token:
credentials = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
credentials.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
credentials = flow.run_console()
# Save the credentials for the next run
with open("token.pickle", "wb") as token:
pickle.dump(credentials, token)
service = build("calendar", "v3", credentials=credentials)
last_check = None
def get_events(calendar_id):
events = (service.events().list(
calendarId=calendar_id,
timeMin=datetime.utcnow().isoformat() + "Z",
maxResults=MAX_EVENTS_PER_CAL,
singleEvents=True,
orderBy="startTime",
)
.execute()
)
return events.get("items", [])
def valid_event(event):
datestr = event["start"].get("dateTime", event["start"].get("date"))
delta = parser.isoparse(datestr).replace(tzinfo=None) - datetime.now()
if delta.days < 0:
# Event is happening now
for attendee in event.get("attendees", []):
if attendee.get("self") and attendee.get("responseStatus") == "accepted":
# At least one attendee, and calendar owner is attending
return True
while True:
if last_check is None or time.monotonic() >= last_check + QUERY_DELAY:
events = [e for e in get_events(CALENDAR_ID) if valid_event(e)]
last_check = time.monotonic()
status = "BUSY" if len(events) > 0 else "FREE"
if blinkt_present:
print(f"Setting blinkt to: {COLOURS[status]}")
blinkt.set_all(*COLOURS[status])
blinkt.show()
print(f"Status: {status}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment