Google Calendar Simple API

repository·master·Indexed 20 days ago

https://github.com/kuzmoyev/google-calendar-simple-api

A Pythonic, object-oriented adapter for the official Google Calendar API. It simplifies the management of calendars, events, attendees, and attachments, and provides tools for handling Access Control Lists (ACL) and OAuth2 authentication using credentials JSON files or pre-loaded Token objects.

Tokens
18.7K
Snippets
57
Records
86
Agent score
71%

What's inside gcsa

  1. How to authenticate multiple Google accounts

    master

    To manage multiple Google accounts within the same application, you must provide a unique token_path for each GoogleCalendar instance. If you do not specify a unique token_path, subsequent instances will overwrite the default token file, causing authentication conflicts.

    # Account 1
    gc_primary = GoogleCalendar(token_path='path/to/tokens/token_primary.pickle')
    
    # Account 2 (Secondary calendar)
    gc_secondary = GoogleCalendar(calendar='f7c1gf7av3g6f2dave17gan4b8@group.calendar.google.com',
                                   token_path='path/to/tokens/token_secondary.pickle')
  2. Understand the difference between Calendars and Calendar List

    master

    In gcsa, it is crucial to distinguish between the Calendars collection and the Calendar List collection:

    • Calendars: Represents the actual calendar objects in existence. Use this collection to create, delete, or update global properties (like title or default_time_zone) that apply to everyone with access to that calendar.
    • Calendar List: Represents the collection of calendars that a specific user has added to their personal view (the left panel in the Google Calendar web UI). Use this to manage user-specific settings like foreground_color, default_reminders, or to add/remove calendars from the user's view.

    All API requests are processed via a GoogleCalendar service instance.

  3. Understand token generation and persistence

    master

    When you run your application for the first time, it will prompt your default browser to authorize access to your calendar.

    • Token Storage: Upon successful authorization, a token.pickle file is created in the same directory as your credentials.json (unless otherwise specified).
    • Disabling Persistence: If you do not want to save the authorization token to a .pickle file, set save_token=False when initializing the GoogleCalendar class.
  4. Understand how Serializers work in gcsa

    master

    The gcsa library provides JSON serializers for all available Google Calendar objects, following the official Google API documentation. While gcsa typically handles serialization automatically under the hood, you can use these serializers manually if you need to convert objects to JSON or vice versa.

    Important Note: The to_json methods ignore read-only fields. Read-only fields are those passed to an object's __init__ with a leading underscore (e.g., Event(_updated=...)).

  5. Create recurrent events with the Recurrence module

    master

    To create recurring events in gcsa, use the gcsa.recurrence.Recurrence module. The module provides methods that return strings in RRULE format. These strings can be passed to the recurrence parameter of an Event object as either a single string or a list of strings.

    There are 8 primary methods for defining recurrence rules:

    • rule: Defines the recurrence rule.
    • exclude_rule: Defines excluded dates/datetimes.
    • dates: Includes specific dates or a list of dates.
    • exclude_dates: Excludes specific dates or a list of dates.
    • times: Includes specific datetimes or a list of datetimes.
    • exclude_times: Excludes specific datetimes or a list of datetimes.
    • periods: Includes specific periods or a list of periods.
    • exclude_periods: Excludes specific periods or a list of periods.

    Note: All exclude_{method} counterparts follow the same format and parameters as their base {method} versions.

    from gcsa.event import Event
    from gcsa.recurrence import Recurrence, DAILY
    
    # Single rule
    Event('Breakfast',
          (1/Jan/2020)[9:00],
          (1/Jan/2020)[10:00],
          recurrence=Recurrence.rule(freq=DAILY))
    
    # Multiple rules (including exclusions)
    Event('Breakfast',
          (1/Jan/2019)[9:00],
          (1/Jan/2020)[9:00],
          recurrence=[
             Recurrence.rule(freq=DAILY),
             Recurrence.exclude_rule(by_week_day=[SU, SA])
          ])
  6. Quickstart: Add events to Google Calendar using GCSA

    master

    To automate adding events to your Google Calendar, use the GoogleCalendar class to manage the connection and the Event class to define individual calendar entries. You can iterate through a range of dates (using libraries like beautiful_date) and call gc.add_event(e) for each event you wish to create.

    This example demonstrates how to schedule a series of daily push-up goals starting from the next Monday.

    from gcsa.google_calendar import GoogleCalendar
    from gcsa.event import Event
    from beautiful_date import D, drange, days, MO
    
    gc = GoogleCalendar()
    
    PUSH_UPS_COUNT = [
        5, 5, 0, 5, 10, 0, 10,
        0, 12, 12, 0, 15, 15, 0,
        20, 24, 0, 25, 30, 0, 32,
        35, 35, 0, 38, 40, 0, 42,
        45, 50
    ]
    
    # starting next Monday (of course)
    # +1 days for the case that today is Monday
    start = D.today()[9:00] + 1 * days + MO
    end = start + len(PUSH_UPS_COUNT) * days
    
    for day, push_ups in zip(drange(start, end), PUSH_UPS_COUNT):
        e = Event(
            f'{push_ups} Push-Ups' if push_ups else 'Rest',
            start=day,
            minutes_before_popup_reminder=5
        )
        gc.add_event(e)
  7. Set or update an event color

    master

    To assign a color to an event, use the color_id field within an Event object. You can set this during event creation or update an existing event by modifying its color_id attribute and calling gc.update_event(event).

    Color IDs are strings representing the specific color (e.g., '4' for Flamingo).

    from gcsa.google_calendar import GoogleCalendar
    from gcsa.event import Event
    
    gc = GoogleCalendar()
    FLAMINGO_COLOR_ID = '4'
    
    # Setting color during creation
    event = Event('Important!', start=start, color_id=FLAMINGO_COLOR_ID)
    event = gc.add_event(event)
    
    # Updating color on an existing event
    event.color_id = FLAMINGO_COLOR_ID
    gc.update_event(event)
  8. Manage the User's Calendar List

    master

    Manage how calendars appear in a user's personal list using CalendarListEntry objects.

    Get the user's calendar list

    Retrieve the collection of calendars in the user's list. You can filter by access role and visibility:

    from gcsa.calendar import AccessRoles
    
    for calendar in gc.get_calendar_list(min_access_role=AccessRoles.READER, show_deleted=True, show_hidden=True):
        print(calendar)

    Get a calendar list entry

    Retrieve the entry for the default calendar or a specific ID:

    # Default
    entry = gc.get_calendar_list_entry()
    
    # By ID
    entry = gc.get_calendar_list_entry('calendar_id')

    Add a calendar to the list

    You can create a CalendarListEntry directly or convert an existing Calendar object:

    from gcsa.calendar import CalendarListEntry
    
    # Direct creation
    entry = CalendarListEntry(calendar_id='calendar_id', summary_override='Holidays in Czechia')
    gc.add_calendar_list_entry(entry)
    
    # From a Calendar object
    from gcsa.calendar import Calendar
    calendar = Calendar(calendar_id='calendar_id', summary='Original Summary')
    entry = calendar.to_calendar_list_entry(summary_override='Holidays in Czechia')
    gc.add_calendar_list_entry(entry)

    Update and Delete list entries

    # Update
    entry.summary_override = 'New Summary'
    gc.update_calendar_list_entry(entry)
    
    # Delete (supports Calendar, CalendarListEntry, or ID)
    gc.delete_calendar_list_entry(calendar)
    gc.delete_calendar_list_entry(entry)
    gc.delete_calendar_list_entry('<calendar_id>')
    from gcsa.google_calendar import GoogleCalendar
    from gcsa.calendar import CalendarListEntry, AccessRoles
    
    gc = GoogleCalendar()
    
    # Get list
    for entry in gc.get_calendar_list(min_access_role=AccessRoles.READER):
        print(entry)
    
    # Add entry
    entry = CalendarListEntry(calendar_id='id', summary_override='New Name')
    gc.add_calendar_list_entry(entry)
    
    # Update entry
    entry.summary_override = 'Updated Name'
    gc.update_calendar_list_entry(entry)
    
    # Delete entry
    gc.delete_calendar_list_entry('id')
  9. Add attendees to a new event

    master

    When creating a new Event, you can specify attendees using the attendees parameter. You can pass a single Attendee object, a single email string, or a list containing both Attendee objects and email strings. If you pass a string, the library will automatically create an Attendee instance for you.

    To configure an Attendee object manually, use the Attendee class which supports display_name and additional_guests.

    from gcsa.attendee import Attendee
    from gcsa.event import Event
    
    # Option 1: Using an Attendee object
    attendee = Attendee(
        'attendee@gmail.com',
        display_name='Friend',
        additional_guests=3
    )
    
    event = Event('Meeting',
                  start=(17/Jul/2020)[12:00],
                  attendees=attendee)
    
    # Option 2: Using a simple email string
    event = Event('Meeting',
                  start=(17/Jul/2020)[12:00],
                  attendees='attendee@gmail.com')
    
    # Option 3: Using a list of mixed types
    event = Event('Meeting',
                  start=(17/Jul/2020)[12:00],
                  attendees=[
                      'attendee@gmail.com',
                      Attendee('attendee2@gmail.com', display_name='Friend')
                  ])
  10. Manage Access Control Lists (ACL) with gcsa

    master

    You can manage Google Calendar access control rules using the gcsa.google_calendar.GoogleCalendar instance. Access control rules are represented by the gcsa.acl.AccessControlRule class. The library provides methods to list, retrieve, add, update, and delete these rules.

    from gcsa.google_calendar import GoogleCalendar
    
    gc = GoogleCalendar()
  11. Add attachments to an existing Event

    master

    To add an attachment to an event that has already been instantiated, use the Event.add_attachment method. This method accepts the attachment details directly as arguments. Note that adding an attachment to the object does not automatically sync it to Google Calendar; you must call GoogleCalendar.update_event to persist the changes.

    # Add attachment to the local event object
    event.add_attachment('My file',
                         file_url='https://bit.ly/3lZo0Cc',
                         mime_type='application/vnd.google-apps.document')
    
    # Persist the changes to Google Calendar
    calendar.update_event(event)