|
import datetime |
|
import os |
|
|
|
from google.oauth2.credentials import Credentials |
|
from google_auth_oauthlib.flow import InstalledAppFlow |
|
from google.auth.transport.requests import Request |
|
from googleapiclient.discovery import build |
|
|
|
|
|
|
|
SCOPES = ['https://www.googleapis.com/auth/calendar'] |
|
|
|
def get_calendar_service(): |
|
creds = None |
|
|
|
if os.path.exists('token.json'): |
|
creds = Credentials.from_authorized_user_file('token.json', SCOPES) |
|
|
|
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) |
|
|
|
with open('token.json', 'w') as token: |
|
token.write(creds.to_json()) |
|
|
|
service = build('calendar', 'v3', credentials=creds) |
|
return service |
|
|
|
def create_event(start_time_str, end_time_str, summary, description, location): |
|
service = get_calendar_service() |
|
start_time = datetime.datetime.fromisoformat(start_time_str) |
|
end_time = datetime.datetime.fromisoformat(end_time_str) |
|
event = { |
|
'summary': summary, |
|
'location': location, |
|
'description': description, |
|
'start': { |
|
'dateTime': start_time.strftime("%Y-%m-%dT%H:%M:%S"), |
|
'timeZone': 'Europe/Paris', |
|
}, |
|
'end': { |
|
'dateTime': end_time.strftime("%Y-%m-%dT%H:%M:%S"), |
|
'timeZone': 'Europe/Paris', |
|
}, |
|
} |
|
|
|
event = service.events().insert(calendarId='primary', body=event).execute() |
|
print('Event created: %s' % (event.get('htmlLink'))) |
|
|
|
|
|
create_event('2024-05-15T09:00:00', '2024-05-15T13:00:00', 'Meeting with Bob', 'Discuss project', 'Cafe Paris') |
|
|