Tech Tips

  1. プログラミング
  2. 1000 view

How to get events from your own Google Calendar using Google Calendar API

Google Calendar API Result from My Bot
I wanted to get events from my Google Calendar to develop a chatbot with Python script but I couldn’t find an article explaining how to do it. So, I’ll share my way.

Contents

To get events from Google Calendar

1. Create Google Cloud Platform account.

If you don’t have Google Cloud Platform account, please create it. I won’t share detail about this because there are so many articles on the internet.

2. Enable Google Calendar API on Google Cloud Platform.

Please move to “APIs & Services” > “Dashboard”.
Please move to “ENABLE APIS AND SERVICES”.
Please type “Google Calendar API” in the search window and select “Google Calendar API”, and then enable Google Calendar API by clicking “ENABLE” button.

3. Create Service Account on Google Cloud Platform.

Service Account is for non-human users. There is detail info in Google Cloud Platform official document.
Service accounts represent non-human users. They’re intended for scenarios where a workload, such as a custom application, needs to access resources or perform actions without end-user involvement. Service accounts differ from normal user accounts in multiple ways:
– They don’t have a password and can’t be used for browser-based sign-in.
– They’re created and managed as a resource that belongs to a Google Cloud project. In contrast, users are managed in a Cloud Identity or Google Workspace account.
– They’re specific to Google Cloud. In contrast, the users managed in Cloud Identity or Google Workspace work across a multitude of Google products and services. This guide presents best practices for managing, using, and securing service accounts.

Best practices for using and managing service accounts
https://cloud.google.com/iam/docs/best-practices-for-using-and-managing-service-accounts
Please move to “APIs & Services” > “Service Accounts”.
And then please click “CREATE SERVICE ACCOUNT”.
Please input service account name and click “CREATE” button.
Other things are optional. So, I’ll skip inputting them because this time is just test. Please click “CONTINUE” and “DONE” buttons.

4. Generate Service Account key.

Please select “Actions” > “Manage keys” at Service Account page.
Please click “ADD KEY” > “Create new key”.
Please click “CREATE” button with “JSON” key type. After that, you can see a dialog box for save and please save and keep your key. The key will be used by Python script.

5. Add Service Account to Google Calendar’s share member.

Please copy Service Account email addoress. After that, Please open Google Calendar and move to “Settings and sharing”.
Please click “Add people” button at “Share with specific people”.
Please input your Service Account email address and click “Send” button.

6. Write Python script.

Now you can get events from your Google Calendar using Python script through your Service Account. So, let’s write Python script. Sample below uses 3.7.9 version and 21.1.2 version for pip. Please install google-api-python-client and google-auth libraries.
pip install google-api-python-client google-auth 
Here is Python script code. You can see calendar_id from Google Calendar’s “Settings and sharing” page (See “Integrate calendar”). And credentials.json is Service Account key.
import datetime, re
import googleapiclient.discovery
import google.auth

# Preparation for Google API
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
calendar_id = 'xxxxx'
gapi_creds = google.auth.load_credentials_from_file('credentials.json', SCOPES)[0]
service = googleapiclient.discovery.build('calendar', 'v3', credentials=gapi_creds)

# Get events from Google Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z'
events_result = service.events().list(
     calendarId=calendar_id, timeMin=now,
     maxResults=5, singleEvents=True,
     orderBy='startTime').execute()

# Pick up only start time, end time and summary info
events = events_result.get('items', [])
formatted_events = [(event['start'].get('dateTime', event['start'].get('date')), # start time or day
     event['end'].get('dateTime', event['end'].get('date')), # end time or day
     event['summary']) for event in events]

# Generate output text
response = '[Closest 5 events]\n'
for event in formatted_events:
     if re.match(r'^\d{4}-\d{2}-\d{2}$', event[0]):
         start_date = '{0:%Y-%m-%d}'.format(datetime.datetime.strptime(event[1], '%Y-%m-%d'))
         response += '{0} All Day\n{1}\n\n'.format(start_date, event[2])
     # For all day events
     else:
         start_time = '{0:%Y-%m-%d %H:%M}'.format(datetime.datetime.strptime(event[0], '%Y-%m-%dT%H:%M:%S+00:00'))
         end_time = '{0:%H:%M}'.format(datetime.datetime.strptime(event[1], '%Y-%m-%dT%H:%M:%S+00:00'))
         response += '{0} ~ {1}\n{2}\n\n'.format(start_time, end_time, event[2])
response = response.rstrip('\n')
print(response)
If you run the script, you can see your events like following.
$ python get_events.py 
[Closest 5 events]
2021-05-30 19:00 ~ 20:00
Test Event 1

2021-05-30 20:45 ~ 21:00
Test Event 2

2021-05-30 21:30 ~ 22:00
Test Event 3

2021-05-30 23:15 ~ 01:00
Test Event 4

2021-06-01 All Day
Test Event 5
That’s it.

プログラミング recent post

  1. How to Upload Program to Arduino Using Platfo…

  2. How to avoid GPG error when using ROS Docker …

  3. Trying to Develop Visited Countries Colored M…

関連記事

PAGE TOP