Files
catlendar/main.py
2025-09-06 23:14:12 -04:00

87 lines
3.2 KiB
Python

import datetime
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]
def get_next_ten():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.json 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.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
"credentials.json", SCOPES
)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("token.json", "w") as token:
token.write(creds.to_json())
try:
service = build("calendar", "v3", credentials=creds)
# Call the Calendar API
now = datetime.datetime.now(tz=datetime.timezone.utc).isoformat()
print("Getting the upcoming 10 events")
events_result = (
service.events()
.list(
calendarId="primary",
timeMin=now,
maxResults=10,
singleEvents=True,
orderBy="startTime",
)
.execute()
)
events = events_result.get("items", [])
if not events:
print("No upcoming events found.")
return
# Prints the start and name of the next 10 eventsa
next_ten = {}
for event in events:
is_datetime = event["start"].get("dateTime") is not None
if is_datetime:
event_start = datetime.datetime.fromisoformat(event["start"].get("dateTime", event["start"].get("date")))
event_end = datetime.datetime.fromisoformat(event["end"].get("dateTime", event["end"].get("date")))
event_date = event_start.strftime("%Y-%m-%d")
formatted_start_time = event_start.strftime("%Y-%m-%d %H:%M")
formatted_end_time = event_end.strftime("%H:%M")
formatted_event_time = f"{formatted_start_time} to {formatted_end_time}"
else:
formatted_event_time = event["start"].get("date")
event_date = f"{formatted_event_time}"
if event_date not in next_ten:
next_ten[event_date] = []
next_ten[event_date].append(f"{formatted_event_time}: {event['summary']}")
print(next_ten)
return next_ten
except HttpError as error:
print(f"An error occurred: {error}")
if __name__ == "__main__":
get_next_ten()