1
votes

I am trying to create an event using Google Calendar API in Python 3 using the documentations provided here:

However, I keep getting error 400 bad request and I have no idea why. My code is as follows:

from pathlib import Path
from pickle import load
from pickle import dump
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from uuid import uuid4
from typing import Dict, List
from oauth2client import file, client, tools


class EventPlanner:
    """
    pass
    """

    def __init__(self, guests: Dict[str, str], schedule: Dict[str, str]):
        guests = [{"email": email} for email in guests.values()]
        service = self._authorize()
        self.event_states = self._plan_event(guests, schedule, service)

    @staticmethod
    def _authorize():
        scopes = ["https://www.googleapis.com/auth/calendar"]
        credentials = None
        token_file = Path("./calendar_creds/token.pickle")

        if token_file.exists():
            with open(token_file, "rb") as token:
                credentials = load(token)

        if not credentials or not credentials.valid:
            if credentials and credentials.expired and credentials.refresh_token:
                credentials.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file('calendar_creds/credentials.json', scopes)
                credentials = flow.run_local_server(port=0)
            with open(token_file, "wb") as token:
                dump(credentials, token)

        calendar_service = build("calendar", "v3", credentials=credentials)

        return calendar_service

    @staticmethod
    def _plan_event(attendees: List[Dict[str, str]], event_time, service: build):
        event = {"summary": "test meeting",
                 "start": {"dateTime": event_time["start"]},
                 "end": {"dateTime": event_time["end"]},
                 "attendees": attendees,
                 "conferenceData": {"createRequest": {"requestId": f"{uuid4().hex}",
                                                      "conferenceSolutionKey": {"type": "hangoutsMeet"}}},
                 "reminders": {"useDefault": True}
                 }
        event = service.events().insert(calendarId="primary", sendNotifications=True, body=event).execute()

        return event


if __name__ == "__main__":
    plan = EventPlanner({"test_guest": "[email protected]"}, {"start": "2020-07-29T20:00:00-4:00",
                                                                          "end": "2020-07-29T20:30:00-4:00"})
    print(plan.event_states)

The first time authentication was done successfully. I also tried the different ways mentioned in the docs but non work. Does anyone know what I am doing wrong? Thanks.

1

1 Answers

1
votes

I think that the reason of your issue is as follows.

Modification points:

  • At RFC3339, for dateTime of start, please modify 2020-07-29T20:00:00-4:00 to 2020-07-29T20:00:00-04:00. Also please modify this for dateTime of end.
  • Please add the time zone.

Modified script:

plan = EventPlanner({"test_guest": "[email protected]"}, {"start": "2020-07-29T20:00:00-04:00", "end": "2020-07-29T20:30:00-04:00"})

And

time_zone = str(get_localzone())
event = {"summary": "test meeting",
         "start": {"dateTime": event_time["start"], "timeZone": time_zone},
         "end": {"dateTime": event_time["end"], "timeZone": time_zone},
         "attendees": attendees,
         "conferenceData": {"createRequest": {"requestId": f"{uuid4().hex}",
                                              "conferenceSolutionKey": {"type": "hangoutsMeet"}}},
         "reminders": {"useDefault": True}
         }

Note:

  • I'm not sure about your time zone. So I used get_localzone() for the modified script. In this case, please also use from tzlocal import get_localzone. If you want to change the time zone, please modify above script.
  • This modified script supposes that you have already been able to create new event to the Google Calendar using Calendar API. Please be careful this.

References: