Skip to content

Instantly share code, notes, and snippets.

@mkakh
Created July 3, 2023 03:44
Show Gist options
  • Save mkakh/a121ee2fe2ffb03363a8e962bd062b67 to your computer and use it in GitHub Desktop.
Save mkakh/a121ee2fe2ffb03363a8e962bd062b67 to your computer and use it in GitHub Desktop.
Set google calendar events on every Monday of the next month
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from datetime import datetime, timedelta
import calendar, os
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar.events']
creds = None
# The file token.json 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.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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.json', 'w') as token:
token.write(creds.to_json())
service = build('calendar', 'v3', credentials=creds)
# Replace with your calendar ID
calendar_id = '###'
year = datetime.now().year
month = datetime.now().month + 1 if datetime.now().month < 12 else 1
# To set the event every monday, calculate the first Monday of the month
first_day, _ = calendar.monthrange(year, month)
m = datetime(year, month, 1) + timedelta(days=(calendar.MONDAY - first_day) % 7)
events = []
# loop while the month has not ended
while m.month == month:
e = datetime(year, month, m.day, 9, 0, 0)
event = {
'summary': 'test',
'start': {
'dateTime': e.isoformat(),
'timeZone': 'Asia/Tokyo',
},
'end': {
'dateTime': (e + timedelta(hours=4)).isoformat(),
'timeZone': 'Asia/Tokyo',
},
}
created_event = service.events().insert(calendarId=calendar_id, body=event).execute()
print("created:", event)
m += timedelta(days=7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment