Para rodar o código abaixo, é preciso criar uma conta de serviço nas credenciais de um projeto no Google e em seguida adicionar o e-mail dessa conta de serviço no calendário desejado (no caso, o nosso próprio e-mail pessoal).
import datetime
import logging
import pprint
from google.oauth2 import service_account
from googleapiclient.discovery import build
from timetailor import consolecolor as ccolor, data
logger = logging.getLogger( __name__ )
def handler_list_and_create (verbose, dryrun):
# Path to the service account credentials JSON file
SERVICE_ACCOUNT_FILE = './service-account.json'
# Define the required scope for the Google Calendar API
SCOPES = [ 'https://www.googleapis.com/auth/calendar' ]
# Create a credentials object from the service account file
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE , scopes = SCOPES )
# Build the service object for the calendar API
service = build( 'calendar' , 'v3' , credentials = credentials)
# Call the Calendar API to list the next 10 events
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print ( 'Getting the upcoming 10 events' )
events_result = service.events().list( calendarId = 'my-personal-email@email.com' , timeMin = now,
maxResults = 10 , singleEvents = True ,
orderBy = 'startTime' ).execute()
events = events_result.get( 'items' , [])
if not events:
print ( 'No upcoming events found.' )
else :
for event in events:
start = event[ 'start' ].get( 'dateTime' , event[ 'start' ].get( 'date' ))
pprint.pprint(event)
print (start, event.get( 'summary' , 'No summary' ))
print ( 'Creating an event' )
# Specify the event detail
event = {
'summary' : 'Google I/O 2023' ,
'location' : '800 Howard St., San Francisco, CA 94103' ,
'description' : 'A chance to hear more about Google \' s developer products.' ,
'start' : {
'dateTime' : '2023-12-22T12:00:00-03:00' ,
'timeZone' : 'America/Sao_Paulo' ,
},
'end' : {
'dateTime' : '2023-12-22T13:00:00-03:00' ,
'timeZone' : 'America/Sao_Paulo' ,
},
}
# Call the Calendar API to create the event on the primary calendar
event = service.events().insert( calendarId = 'my-personal-email@mail.com' , body = event).execute()
print ( f 'Event created: { event.get( "htmlLink" ) } ' )