首页 > 解决方案 > 替代谷歌创建日历事件的代码片段?

问题描述

我正在尝试通过谷歌的 API 调用创建日历事件。根据我必须使用的文件:

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.readonly']


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)

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

    # Call the Calendar API
    now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
    print('Getting the upcoming 10 events')
    events_result = service.events().list(calendarId='primary', timeMin=now,
                                        maxResults=10, singleEvents=True,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('No upcoming events found.')
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(start, event['summary'])


if __name__ == '__main__':
    main()

但是,我正在构建一个 Alexa 技能,其中 access_token调用 handler_input.request_envelope.context.system.user.access_token. 因此,我将代码调整为如下所示:

import os
import pickle
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'Timer_Hello_Layered/creds.json'     
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']

            
event = {
'summary': 'Test',
'location': 'At home',
'description': 'A chance to hear more about Google\'s developer products.',
'start': {
    'dateTime': '2020-07-29T12:12:10',
    'timeZone': 'America/Los_Angeles',
},
'end': {
    'dateTime': '2020-07-29T12:32:47',
    'timeZone': 'America/Los_Angeles',
}
}
#way of retrieving access token with alexa skill
creds = handler_input.request_envelope.context.system.user.access_token
#have to add /tmp/ when dealing with AWS lambda
SCreds = pickle.dump(creds, open("/tmp/save.pickle","wb")) 
service = build('calendar', 'v3', credentials= SCreds, cache_discovery=False)    
event = service.events().insert(calendarId='primary', body=event).execute()

我用这段代码意识到,事件没有被创建(尽管没有错误),因为我没有在creds.json任何地方传递 SCOPES 或文件。但是,与此同时,alexa 不允许我运行 creds = flow.run_local_server(port=0).

还有这个文件,但我不知道它是否是解决方案。即使是,也没有用于 creds.json 的参数传递给。

有没有办法解决?我非常感谢您的帮助,因为我已经在这方面存货超过 2 周了 :((

标签: pythongoogle-apigoogle-calendar-apialexaalexa-skills-kit

解决方案


推荐阅读