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 required to access and manipulate calendar events SCOPES = ['https://www.googleapis.com/auth/calendar'] def get_calendar_service(): creds = None # Load existing credentials if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If no valid credentials are 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.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'))) # Example of adding an event create_event('2024-05-15T09:00:00', '2024-05-15T13:00:00', 'Meeting with Bob', 'Discuss project', 'Cafe Paris')