user13234289
user13234289

Reputation:

Retrieve summary information from google calendar API

I have a code that works 'perfectly'. I can add an event in my calendar, but before adding it, it checks if the time slot is taken. IF time slot not taken, then it adds the event. IF it's taken, it tells me the details of the event already existing.

the problem is that there are several people who can have appointments in the same time range, but my code will not let it happen. I need my code to check the 'summary' because it will contain the name of the busy person. Sorry for my english, im french so here is an example below.

Example of what I need : If there is already a registered appointment in my calendar for James (Summary) at 10am to 1pm. And I decide to add a new appointment for Mary at 10am to 1pm, it should let me add it. Because they are two different person. BUT, if I wanna add another appointment for James for 10am again, obviously it wont let me since he already has an appointment in this time slot.

This is my code so far that works (see paragraph 1 to read what it does)

IMPORTS:

from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

TOKEN :

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar']


def main():
    """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.pickle 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.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # 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.pickle', 'wb') as token:
            pickle.dump(creds, token)

ADD EVENT IF THERE IS NO EVENTS AT REQUIRED TIME:

service = build('calendar', 'v3', credentials=creds)

    event_summary = 'Jad'
    event_location = 'H7N 5H9'
    event_description = 'Test'
    event_start = '2020-04-29T14:00:00-00:00'
    event_end = '2020-04-29T16:00:00-00:00'

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
    print('Looking if already created - if not, will create')
    events_result = service.events().list(calendarId='primary', timeMin=event_start,
                                          maxResults=1, singleEvents=True,
                                          orderBy='startTime').execute()
    events = events_result.get('items',[])

    if not events :

        event = {
            'summary': event_summary,
            'location': event_location,
            'description': event_description,
            'start': {
                'dateTime': event_start,
                'timeZone': 'America/New_York',
            },
            'end': {
                'dateTime': event_end,
                'timeZone': 'America/New_York',
            },
            'reminders': {
                'useDefault': True,
            },

        }

        event = service.events().insert(calendarId='primary', body=event).execute()

        print('new event created')

IF EVENT ALREADY EXIST, SHOW EVENT :

    for event in events:
        print('Cannot create new event because time slot already taken by : ')
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'], event['location'])

if __name__ == '__main__':
    main()

Upvotes: 0

Views: 576

Answers (1)

Sri
Sri

Reputation: 2318

So I think the answer here is pretty straightforward. First lets examine your code.

  1. You create a sample event with the given information.
  2. You check if there is an event at that time.
    1. If there is no event, you create it.
    2. If there is an event, you show the event that exists already.

You already have the code for creating and submitting an event, and the code for reading events. Here is what I suggest you do.

  1. If there is an event, loop through the events that are there.
  2. Check the event['summary'] value of each event, and see if it matches event_summary, the variable you defined earlier. You would want to use a boolean flag of some sort to indicate whether you found a match or not. If there is a match, set the flag and break the loop.
  3. Once the loop has completed, check the flag to see if you found a match or not.
    1. If you found a match, then the timeslot is taken and you can print the information accordingly.
    2. If you did not find a match, then you can submit your new event (the same way you would submit it as if an event did not exist)

Edit: The solution would look something like this.

service = build('calendar', 'v3', credentials=creds)

    event_summary = 'Jad'
    event_location = 'H7N 5H9'
    event_description = 'Test'
    event_start = '2020-04-29T14:00:00-00:00'
    event_end = '2020-04-29T16:00:00-00:00'

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z'  # 'Z' indicates UTC time
    print('Looking if already created - if not, will create')
    events_result = service.events().list(calendarId='primary', timeMin=event_start,
                                          maxResults=1, singleEvents=True,
                                          orderBy='startTime').execute()
    events = events_result.get('items',[])

    found_match = False
    for event in events:
        if event['summary'] == event_summary:
            print('Cannot create new event because time slot already taken by : ')
            start = event['start'].get('dateTime', event['start'].get('date'))
            print(start, event['summary'], event['location'])
            found_match = True
            break

    if not(found_match):
        event = {
            'summary': event_summary,
            'location': event_location,
            'description': event_description,
            'start': {
                'dateTime': event_start,
                'timeZone': 'America/New_York',
            },
            'end': {
                'dateTime': event_end,
                'timeZone': 'America/New_York',
            },
            'reminders': {
                'useDefault': True,
            },
        }
        event = service.events().insert(calendarId='primary', body=event).execute())

if __name__ == '__main__':
    main()

Upvotes: 1

Related Questions