1
votes

I built an app using Python and its connected to the google calendar API.

I don't understand why I get this error "Google Calendar API: 403 Calendar Usage Limits Exceeded Using Service Account"

I barely added events, maybe 300 in a week.

I used to have an old account and I added thousands in days. Now, with this new, free account, It gave me this error!

What can I do? Is it fixable?!

Initiate Calendar Service :

def initiate_calendar_service():
    """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)

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

ADD EVENT:


        for i in range(1):

            startStrip = datetime.datetime.strptime(event_start, "%Y-%m-%dT%H:%M:%S")
            endStrip = datetime.datetime.strptime(event_end, "%Y-%m-%dT%H:%M:%S")
            dayOfWeek = startStrip + datetime.timedelta(days=i)
            # les bons formats
            currentStart = str(startStrip + datetime.timedelta(days=i)).replace(" ", "T")
            currentEnd = str(endStrip + datetime.timedelta(days=i)).replace(" ", "T")
            calendarEnd = str(endStrip + datetime.timedelta(days=i + 1)).replace(" ", "T")


            events_result = service.events().list(calendarId='primary', timeMin=currentStart + "-00:00",
                                                  maxResults=30, timeMax=calendarEnd + "-00:00",
                                                  singleEvents=True, orderBy='startTime').execute()
            events = events_result.get('items', [])

            currentEmployees = []
            for event in events:
                currentEmployees.append(event['summary'])

            if employee in currentEmployees:
                event_done = False
                event['summary'] = employee
                
                for event in events:
                   if str2datetime(currentStart) <= str2datetime(event['end']['dateTime'].split('+')[0]) and str2datetime(currentEnd) >= str2datetime(event['start']['dateTime'].split('+')[0]):
                    event_done = False
                    print(employee + ' est occupé')
                    break
                   else:
                      event_done = True
                      break

            if employee not in currentEmployees:
                event_done = True

            if event_done:
                option = show_message_box(QMessageBox.Critical,
                                      "Confirmation",
                                      "Voulez-vous bloquer cette plage horraire?"\
                                      "L'employé : \"" + employee + "\" sera marqué comme indisponible en raison de : " + reason, \
                                      "Nom de l'employé: " + employee + "\n" \
                                      "Raison: " + reason + "\n" \
                                      "À partir du : " + currentStart + "\n" \
                                      "À ce jour " + currentEnd + "\n"
                                      )

                if option == QMessageBox.Yes:
                    event_done = True
                else:
                    print("Événement ignoré!")
                    event_done = False
                    break

                if event_done:
                    event = {
                        'summary': employee,
                        'location': location,
                        'description': reason,
                        'start': {
                            'dateTime': currentStart,
                            'timeZone': 'America/New_York',
                        },
                        'end': {
                            'dateTime': currentEnd,
                            'timeZone': 'America/New_York',
                        },
                        'attendees': [
                            {'email': event_email},
                        ],
                        'reminders': {
                            'useDefault': True,
                        },
                    }
                    register_event(service, event)

            else:
                second_message_box(QMessageBox.Critical,
                                      "ATTENTION!",
                                      "L'inspecteur " + employee + " est déjà occupé à ce moment-là.""\n" \
                                      "Veuillez essayer une autre plage horraire.", QMessageBox.Ok)

Additional information:

I had one account, and in 1 month, I did 3041 calendar.events.list requests. and 181 calendar.events.insert.

I had NO problem.

This time, with a new account, in 2 days, I did 730 calendar.events.list requests, and 175 calendar.events.insert. Is 175 event insert is a lot in 2 days??

This was the account that gave me the error :

https://media.discordapp.net/attachments/424313024829194252/724686224500981920/unknown.png?width=1922&height=622

1

1 Answers

0
votes

You can see from the documentation for Calendar usage limits exceeded:

The user reached one of the Google Calendar limits in place to protect Google users and infrastructure from abusive behavior.

The limits are listed here and it is important that

For G Suite free edition and G Suite trial accounts, limits are lower than those stated above.

and

At the end of your free trial period, Calendar use limits are automatically increased when your domain is cumulatively billed for at least USD $30 (or equivalent).

So basically, if you have a new account and are still in the trial period your limits are lower than after the trial limit (the exact limits are not specified by Google), this is why you ran into this issue with your new account.

Apart from the fact that "spamming for testing" is in general not a very good practice and can raise the supicion for "abusive behavior", the limits are stricter for external guests, so for testing purposes you should invite users from your own domain instead of external.

To avoid hititng limits it is also recommended to use the exponential backoff to reduce the speed of your requests.