[创建Google事件之前验证它是否已存在

问题描述 投票:5回答:1

我使用了Google文档,以便能够使用python编码添加Google日历事件。

但是我想要的是能够在添加事件之前验证X日期时隙是否为空。

这是我的代码:

from __future__ import print_function
from datetime 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

SCOPES = ['https://www.googleapis.com/auth/calendar']

event_summary = 'test123'
event_location = 'h4n1p9'
event_start = '2020-04-22T05:00:00-00:00'
event_end = '2020-04-22T08:00:00-00:00'

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

}

class PostToGoogleCalendar:

    def __init__(self):
        self.creds = None
        if os.path.exists('token.pickle'):
            with open('token.pickle', 'rb') as token:
                self.creds = pickle.load(token)
        if not self.creds or not self.creds.valid:
            if self.creds and self.creds.expired and self.creds.refresh_token:
                self.creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                self.creds = flow.run_local_server()
            with open('token.pickle', 'wb') as token:
                pickle.dump(self.creds, token)

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

    def get_events(self):
        now = datetime.utcnow().isoformat() + 'Z'
        events_result = self.service.events().list(calendarId='primary', timeMin=now,
                                                   maxResults=500, singleEvents=True,
                                                   orderBy='startTime').execute()
        return events_result.get('items', [])

    def create_event(self, new_event):
        if not self.already_exists(new_event):
            event = self.service.events().insert(calendarId='primary', body=new_event).execute()
            return event.get('htmlLink')
        else:
            return 'Event Already Exists'

    def already_exists(self, new_event):
        events = self.get_date_events(new_event['start']['dateTime'], self.get_events())
        event_list = [new_event['summary'] for new_event in events]
        if new_event['summary'] not in event_list:
            return False
        else:
            return True

    def get_date_events(self, date, events):
        lst = []
        date = date
        for event in events:
            if event.get('start').get('dateTime'):
                d1 = event['start']['dateTime']
                if d1 == date:
                    lst.append(event)
        return lst



此代码用于验证2020-04-22中的事件。如果在所选时间有一个事件,则返回找到该事件的消息,如果没有,则在日历中创建该事件。

但是它不起作用,我没有错误,但是什么也没有发生。.

python google-calendar-api
1个回答
0
投票

这是答案。

如果时隙空闲则添加事件,否则,则显示注册的事件。


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

# 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 1 event 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)

    event_summary = 'Test_Cal'
    event_location = 'h4n1p9'
    event_description = 'test'
    event_start = '2020-04-29T19:00:00-00:00'
    event_end = '2020-04-29T20: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': '',
            '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')

    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()

如果可以修改现有代码,请随时发表评论。

© www.soinside.com 2019 - 2024. All rights reserved.