Reputation: 1
In google calendar interface, using the "Meet with…" section, I am able to see meetings and the information about those meetings from any users in the workplace without them sharing their calendars with me. I am trying to achieve the same results through the google calendar api.
I'm developing a project on Google Colab that uses the Google Calendar API to fetch calendar information for all users in our workplace. My goal is to access users' calendar data without requiring them to individually share their calendars with a service account. Although I don't have administrative privileges, the superadmin has enabled admin access for the service account.
What I Have Configured the following using Python Quickstart:
Enabled Scopes:
"https://www.googleapis.com/auth/calendar.readonly",
"https://www.googleapis.com/auth/admin.directory.user.readonly",
"https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly",
"https://www.googleapis.com/auth/calendar.events.readonly",
"https://www.googleapis.com/auth/calendar.settings.readonly"
The delegated admin is the service account on the project, which also has admin permissions in the workplace. I can list all the users in the organization, but I’m having trouble retrieving their full calendar data. For one user who explicitly shared their calendar with the service account, I only receive limited details such as dateTime, but no summary (title) or attendance information.
What else might be missing in my setup or configuration that is preventing full access to users’ calendar data? Are there additional scopes, settings, or API configurations that I need to consider?
Any help or guidance would be greatly appreciated!
Here is my code for reference
import traceback
import datetime
from google.oauth2 import service_account
from googleapiclient.discovery import build
import os.path
# Define the required scope for the Calendar API.
SCOPES = [
"https://www.googleapis.com/auth/calendar.readonly",
"https://www.googleapis.com/auth/admin.directory.user.readonly",
"https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly",
"https://www.googleapis.com/auth/calendar.events.readonly",
"https://www.googleapis.com/auth/calendar.settings.readonly"
]
# Path to service account key file.
SERVICE_ACCOUNT_FILE = '***/***/***'
# The delegated admin email (test with this account).
DELEGATED_ADMIN = '**********.gserviceaccount.com'
def get_all_users():
try:
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES
).with_subject(DELEGATED_ADMIN)
directory_service = build("admin", "directory_v1", credentials=creds)
results = directory_service.users().list(domain="company.com", maxResults=100).execute()
users = results.get("users", [])
return [user["primaryEmail"] for user in users]
except Exception as e:
print(f"Error getting users: {e}")
traceback.print_exc()
return []
def get_events_for_user(user_email):
try:
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES
).with_subject(DELEGATED_ADMIN)
calendar_service = build("calendar", "v3", credentials=creds)
# Check if the user has a primary calendar
try:
calendar_service.calendars().get(calendarId=user_email).execute()
except Exception as e:
print(f" Skipping {user_email}: No primary calendar found or access denied.")
return []
# Look back 30 days
time_min = (datetime.datetime.utcnow() - datetime.timedelta(days=30)).isoformat() + "Z"
# Fetch events list
events_result = calendar_service.events().list(
calendarId=user_email,
timeMin=time_min,
maxResults=5,
singleEvents=True,
orderBy="startTime"
).execute()
events = events_result.get("items", [])
if not events:
return []
return events
except Exception as e:
print(f"Error fetching events for {user_email}: {e}")
traceback.print_exc()
return []
def main():
user_emails = get_all_users()
if not user_emails:
print("No users found. Check your permissions and delegation.")
return
print(f"Found {len(user_emails)} users.\n")
for email in user_emails:
print(f"Events for {email}:")
try:
events = get_events_for_user(email)
if not events:
print(" No events found in the last 30 days.")
else:
for event in events:
start = event["start"].get("dateTime", event["start"].get("date"))
title = event.get("summary", "No Title")
status = event.get("status", "Unknown") # Event status (confirmed, tentative, canceled)
# Extract attendees safely
attendee_emails = []
if "attendees" in event:
attendee_emails = [att.get("email", "Unknown") for att in event["attendees"]]
print(f" {start} | Title: {title} | Status: {status} | Attendees: {', '.join(attendee_emails) if attendee_emails else 'None'}")
except Exception as e:
print(f" Error fetching events: {str(e)}")
traceback.print_exc()
print("\n")
if __name__ == "__main__":
main()
and the output where joe doe has shared his calendar with the service account
Found 10 users.
Events for [email protected]:
Skipping [email protected]: No primary calendar found or access denied.
No events found in the last 30 days.
Events for [email protected]:
2025-02-03T09:00:00-05:00 | Title: No Title | Status: confirmed | Attendees: None
2025-02-04T14:00:00-05:00 | Title: No Title | Status: confirmed | Attendees: None
2025-02-05T15:00:00-05:00 | Title: No Title | Status: confirmed | Attendees: None
2025-02-06T09:15:00-05:00 | Title: No Title | Status: confirmed | Attendees: None
2025-02-06T14:00:00-05:00 | Title: No Title | Status: confirmed | Attendees: None
Upvotes: 0
Views: 32