Easy Google Calendar Integration with Python.
Ever wished you could automate your Google Calendar tasks using Python? Well, you’re in luck! In this beginner-friendly guide, we’ll explore the wonders of Google Calendar integration using a simple Python script.
Getting Started
Step 1: Set Up Your Environment
Before diving into the code, ensure you have the necessary tools installed. Open your terminal and run the following command:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
Step 2: Authentication
The first thing our script needs to do is talk to Google Calendar. To do this, we’ll use the googleapiclient
library to authenticate our script.
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.oauth2.credentials import Credentials
# Define the scope
scopes = ['https://www.googleapis.com/auth/calendar']
# Set up the authentication flow
flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", scopes=scopes)
credentials = flow.run_local_server()
# Save credentials for future use
import pickle
pickle.dump(credentials, open("token.pkl", "wb"))
Building the Calendar Service
Now that we’re authenticated, let’s build our connection to Google Calendar.
credentials = pickle.load(open("token.pkl", "rb"))
service = build("calendar", "v3", credentials=credentials)
Exploring Your Calendars
Let’s dip our toes into the world of calendars. The script fetches a list of your calendars, and we print out information about the second calendar in the list.
result = service.calendarList().list().execute()
calendar_id = result['items'][1]['id']
print(result['items'][1])
Checking Your Events
Next up, let’s see what events are happening in that calendar.
result = service.events().list(calendarId=calendar_id, timeZone="Asia/kolkata").execute()
latest_event = result['items'][-1]
print(latest_event)
Creating Your Own Event
Now comes the fun part! Let’s create our own calendar event. In this example, we’re scheduling a sports event.
from datetime import datetime, timedelta
start_time = datetime(2023, 9, 2, 15, 0, 0)
end_time = start_time + timedelta(hours=4)
timezone = 'Asia/Kolkata'
event = {
'summary': 'Developer's event',
'location': '800 Howard St., San Francisco, CA 94103',
'description': 'A chance to hear more about Google\'s developer products.',
'start': {
'dateTime': start_time.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'end': {
'dateTime': end_time.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': timezone,
},
'attendees': [
{'email': 'abc@gmail.com'}#fill your friend's email
],
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
event = service.events().insert(calendarId=calendar_id, body=event).execute()
Creating a Custom Event
Not into sports? No worries! Here’s a function that lets you create a generic event based on your preferences.
import datefinder
def create_event(start_time_str, summary, duration=1, description=None, location=None):
matches = list(datefinder.find_dates(start_time_str))
if len(matches):
start_time = matches[0]
end_time = start_time + timedelta(hours=duration)
event = {
'summary': summary,
'location': location,
'description': description,
'start': {
'dateTime': start_time.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': 'Asia/Kolkata',
},
'end': {
'dateTime': end_time.strftime("%Y-%m-%dT%H:%M:%S"),
'timeZone': 'Asia/Kolkata',
},
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
return service.events().insert(calendarId='primary', body=event).execute()
create_event("2 September 2 pm", "Meeting")
Wrapping Up
And there you have it! A simple Python script that can interact with your Google Calendar. Feel free to customize it, add your events, and explore the world of automation.
Happy coding! 🚀