我尝试通过 Google Calendar API 执行自动化任务并收到以下错误消息:
C:\Users\Documents\Calendar Add-On>python calendar_v2.py
Traceback (most recent call last):
File "C:\Users\Documents\Calendar Add-On\calendar_v2.py", line 68, in <module>
create_events(calendar_id)
File "C:\Users\Documents\Calendar Add-On\calendar_v2.py", line 46, in create_events
events_result = service.events().list(
File "C:\Users\anaconda3\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\anaconda3\lib\site-packages\googleapiclient\http.py", line 938, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin=2024-05-15T20%3A43%3A15.671352&timeMax=2024-06-14T20%3A43%3A15.671352&singleEvents=true&alt=json returned "Bad Request". Details: "[{'domain': 'global', 'reason': 'badRequest', 'message': 'Bad Request'}]">
我似乎不明白为什么它给我这个错误消息。
我已经尝试了很多次代码,但总是回到这个问题。我的代码的简短片段(我显然省略了日历 ID 和 .json 文件名):
from google.oauth2 import service_account
from googleapiclient.discovery import build
from datetime import datetime, timedelta
# Define the service account credentials
SERVICE_ACCOUNT_FILE = r'path_to_service_account_file.json'
SCOPES = ['https://www.googleapis.com/auth/calendar']
# Authenticate and build the Calendar API client
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('calendar', 'v3', credentials=credentials)
# Function to add buffer before and after each event
def add_event_buffer(event):
start_time = event['start'].get('dateTime')
end_time = event['end'].get('dateTime')
if start_time and end_time:
start_dt = datetime.fromisoformat(start_time)
end_dt = datetime.fromisoformat(end_time)
buffer_time = timedelta(minutes=10)
buffered_start_time = (start_dt - buffer_time).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
buffered_end_time = (end_dt + buffer_time).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
event['start']['dateTime'] = buffered_start_time
event['end']['dateTime'] = buffered_end_time
event['summary'] = 'Travel Time - ' + event['summary']
return event
# Function to create buffered events on the calendar
def create_buffered_events(calendar_id):
try:
start_time = datetime.now().isoformat()
end_time = (datetime.now() + timedelta(days=30)).isoformat()
events_result = service.events().list(
calendarId=calendar_id,
timeMin=start_time,
timeMax=end_time,
singleEvents=True
).execute()
events = events_result.get('items', [])
if not events:
print('No events found.')
else:
for event in events:
if 'Travel Time' in event.get('summary', ''):
print(f'Skipping buffered event for: {event["summary"]} (already buffered)')
continue
buffered_event = add_event_buffer(event)
if 'id' in event:
service.events().update(calendarId=calendar_id, eventId=event['id'], body=buffered_event).execute()
print(f'Buffered event updated for: {buffered_event["summary"]}')
else:
service.events().insert(calendarId=calendar_id, body=buffered_event).execute()
print(f'Buffered event created for: {buffered_event["summary"]}')
except Exception as e:
print("An error occurred:", e)
raise
# Example usage
if __name__ == '__main__':
calendar_id = '[email protected]'
create_buffered_events(calendar_id)
在你的脚本中,进行以下修改怎么样?请修改
create_buffered_events
如下。
start_time = datetime.now().isoformat()
end_time = (datetime.now() + timedelta(days=30)).isoformat()
start_time = datetime.now().isoformat() + "Z"
end_time = (datetime.now() + timedelta(days=30)).isoformat() + "Z"