A Quick Hack for Automating Google Calendar Events and Meetings

Zabir Al Nazi Nabil
5 min readMay 2, 2024

--

Photo Credit: Pexels

Backstory:

When you’re in the thick of managing a machine learning system, every alert can feel like a fire drill. In my new machine learning team, which was small but spread across three continents, setting up an effective on-call system was quite a challenge. Early on, I whipped up a rather makeshift solution. Every time we got a critical or high-priority alert, it triggered a Google Calendar event that automatically invited team members to a call. We heavily rely on Google’s tools (from communication tools to cloud), so naturally, I wanted a quicker way to whip up a Google Calendar event and get a Meet call going directly from our high-priority Slack alerts. I even tweaked it a bit by adding heuristics to tag the most relevant people and adjust the meeting times based on the alert’s metadata.

It was a bit rough around the edges, but this simple, hacky approach really came through for us. We eventually upgraded to a more sophisticated on-call monitoring system, but this initial setup kept us going for the first few months and made sure we stayed on top of urgent issues without missing a beat.

So, I started by setting up access to the Google Calendar API and handling OAuth2 authentication.

Prerequisites:

  • Google Cloud Platform Project: You need a project with the Calendar API enabled.
  • OAuth 2.0 Credentials: These are necessary for authentication. Follow these steps to get them:
  • Go to the Google Cloud Console.
  • Select your project, navigate to “APIs & Services”, then to “Credentials”.
  • Click on “Create Credentials” and select “OAuth client ID”.
  • Configure the consent screen if prompted.
  • Choose the application type (e.g., Web application) and note down your client ID and client secret.
  • Download the JSON file containing these credentials.
Create the app in OAuth consent screen
Add scopes (not mendatory)
Add test users (outside your organisation)
Create OAuth client ID
Download JSON secret

For this tutorial, I have created a test app with some external test users (outside your organisation). Once you have downloaded the JSON secret, you can set up your VM by installing the required packages.

Install Required Libraries: You’ll need the google-auth, google-auth-oauthlib, pytz, and google-auth-httplib2 libraries, as well as the google-api-python-client. Install them using pip:

pip install — upgrade google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client pytz

Once you run the following script and authenticate, you should be able to see the events in Google Calendar with a google meet link.

Script:

from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from datetime import datetime, timedelta
import pytz

# Function to authenticate and create a service
def get_calendar_service():
scopes = ['https://www.googleapis.com/auth/calendar']
flow = InstalledAppFlow.from_client_secrets_file('client_secret.json', scopes=scopes)
credentials = flow.run_local_server(port=0)
return build('calendar', 'v3', credentials=credentials)

# Get Alert time + offset
def get_alert_time():
# hadcoded example
return '2024-05-03 18:00'

# Get Alert time + offset
def get_alert_duration():
# hadcoded example
return 30

# Get Alert time + offset
def get_relevant_teammembers():
# hadcoded example
return ['abc@xyz', 'xyz@abc']

# Get Alert time + offset
def get_meeting_title():
# hadcoded example
return 'Team Sync x 2'


# Function to create an event
def create_event(service, emails, start_time_str, duration_min, title):
# Timezone
timezone = pytz.timezone('Asia/Dhaka')
# Parse the datetime
start_time = timezone.localize(datetime.strptime(start_time_str, "%Y-%m-%d %H:%M"))
end_time = start_time + timedelta(minutes=duration_min)

event = {
'summary': title,
'start': {
'dateTime': start_time.isoformat(),
'timeZone': 'Asia/Dhaka',
},
'end': {
'dateTime': end_time.isoformat(),
'timeZone': 'Asia/Dhaka',
},
'attendees': [{'email': email} for email in emails],
'conferenceData': {
'createRequest': {
'conferenceSolutionKey': {'type': 'hangoutsMeet'},
'requestId': f"some-random-string-{datetime.now().isoformat()}"
}
}
}
return service.events().insert(calendarId='primary', body=event, conferenceDataVersion=1).execute()

# Example usage
def schedule_meeting(emails, start_time, duration, title):
service = get_calendar_service()
event = create_event(service, emails, start_time, duration, title)
print('Meeting scheduled successfully:')
print(f"Meeting ID: {event['id']}")
print(f"Meeting Link: {event['hangoutLink']}")

# Replace with your details
emails = get_relevant_teammembers() # List of string
start_time = get_alert_time() # YYYY-MM-DD HH:MM format
duration = get_alert_duration() # Duration in minutes
title = get_meeting_title() # Meeting title

# Call the function
schedule_meeting(emails, start_time, duration, title)

Here, I am using flow.run_local_server() for testing, which opens a web browser for user interaction, you can use a service account for server-to-server interactions without any user presence. This method is particularly useful for automated tasks and scripts.

Here’s how you can modify your script to use a service account for authentication:

Create a Service Account

  1. Go to the Google Cloud Console (https://console.cloud.google.com/).
  2. Navigate to “IAM & Admin” > “Service accounts”.
  3. Click “Create Service Account”, enter a name, description, and then click “Create”.
  4. Grant the service account necessary roles (e.g., Calendar API access). Then click “Continue”.
  5. Click “Done” after the roles are set.
  6. Click on the created service account, go to “Keys”, and add a new key. Choose JSON, and the key file will be downloaded to your machine.
from google.oauth2 import service_account
from googleapiclient.discovery import build

def get_calendar_service():
scopes = ['https://www.googleapis.com/auth/calendar']
service_account_file = 'service_account.json' # Path to your service account key file

credentials = service_account.Credentials.from_service_account_file(
service_account_file, scopes=scopes)

return build('calendar', 'v3', credentials=credentials)

--

--