Create a program in Python that enables a two-way sync between Airtable and Google calendar. I want to sync creation of new records, creation of new calendar events, updates on new records, updates on calendar events, deleting records with deleting calendar events and vice versa
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating a two-way sync between Airtable and Google Calendar involves several steps, including setting up APIs for both services, handling authentication, and implementing the synchronization logic. Below is a simplified Python program outline that achieves this. Please note, for brevity and due to the complexity of handling all edge cases in a single response, this example focuses on the core functionality. You'll need to expand error handling and possibly optimize the sync process based on your specific requirements.
Prerequisites
Airtable API Key and Base ID:
Go to your Airtable account, find the API key in your account settings.
Identify the Base ID of the base you want to sync.
Google Calendar API Credentials:
Enable the Google Calendar API in the Google Cloud Console.
import os
from pyairtable import Table
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import pickle
import os.path
import datetime
import schedule
import time
# Airtable Setup
AIRTABLE_API_KEY = 'YOUR_AIRTABLE_API_KEY'
AIRTABLE_BASE_ID = 'YOUR_AIRTABLE_BASE_ID'
TABLE_NAME = 'YOUR_TABLE_NAME' # Name of the table in Airtable
# Google Calendar Setup
SCOPES = ['https://www.googleapis.com/auth/calendar']
CALENDAR_ID = 'primary' # or a specific calendar ID
# Paths
TOKEN_PATH = 'token.pickle'
CREDENTIALS_PATH = 'credentials.json'
def get_airtable_table():
"""Returns an Airtable table object for interactions."""
return Table(AIRTABLE_API_KEY, AIRTABLE_BASE_ID, TABLE_NAME)
def get_google_calendar_service():
"""Sets up and returns the Google Calendar API service object."""
creds = None
# The file token.pickle 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_PATH):
with open(TOKEN_PATH, 'rb') as token:
creds = pickle.load(token)
# 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_PATH, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(TOKEN_PATH, 'wb') as token:
pickle.dump(creds, token)
return build('calendar', 'v3', credentials=creds)
Step 2: Sync Functions
python
Step 3: Running the Sync
To keep things simple, the deletion sync and continuous running aspects are not fully implemented in the above code. For a production environment, consider the following enhancements:
Continuous Running: Use a scheduler like schedule or apscheduler in Python to periodically run airtable_to_google_calendar() and google_calendar_to_airtable().
Deletion Sync: Utilize Google Calendar's Push Notifications (Webhooks) to trigger deletions in Airtable and vice versa. This requires setting up serverless functions or an always-running server to receive these notifications.
Error Handling: Implement comprehensive error handling to manage potential issues like network errors, API rate limits, or field mapping inconsistencies.
Example Running the Sync Once
python
def run_sync():
airtable_to_google_calendar()
google_calendar_to_airtable()
delete_airtable_record_if_calendar_event_deleted()
delete_google_calendar_event_if_airtable_record_deleted()
if __name__ == '__main__':
# Run sync once at the start
run_sync()
# Schedule the sync to run every 5 minutes
schedule.every(5).minutes.do(run_sync)
while True:
schedule.run_pending()
time.sleep(1)
Note: This code serves as a foundational example. Depending on your specific Airtable schema, Google Calendar setup, and the volume of data, you may need to adjust the code, especially for handling deletions and updates more elegantly.
def airtable_to_google_calendar():
"""
Syncs new or updated records from Airtable to Google Calendar.
"""
try:
airtable_table = get_airtable_table()
calendar_service = get_google_calendar_service()
# Fetch new/updated records from Airtable
airtable_records = airtable_table.all(view='Your_View_Name', formula='AND({Created At} >= NOW() - 1, {Google Calendar ID} = "")')
for record in airtable_records:
# Assuming you have fields like 'Event Name', 'Start Time', 'End Time'
event_body = {
'summary': record['fields'].get('Event Name', 'No Title'),
'start': {'dateTime': record['fields'].get('Start Time', '')},
'end': {'dateTime': record['fields'].get('End Time', '')},
}
# Create event on Google Calendar
event = calendar_service.events().insert(calendarId=CALENDAR_ID, body=event_body).execute()
# Update Airtable record with Google Calendar Event ID
airtable_table.update(record['id'], {'Google Calendar ID': event.get('id')})
except Exception as e:
print(f"Error in airtable_to_google_calendar: {e}")
def google_calendar_to_airtable():
"""
Syncs new or updated events from Google Calendar to Airtable.
"""
try:
calendar_service = get_google_calendar_service()
airtable_table = get_airtable_table()
# Fetch new/updated events from Google Calendar
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
events_result = calendar_service.events().list(calendarId=CALENDAR_ID, timeMin=now, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
for event in events:
# Check if event already exists in Airtable
existing_records = airtable_table.all(formula=f"{{Google Calendar ID}} = \"{event['id']}\"")
if not existing_records:
# Create new record in Airtable
new_record = {
'Event Name': event.get('summary', 'No Title'),
'Start Time': event['start'].get('dateTime', ''),
'End Time': event['end'].get('dateTime', ''),
'Google Calendar ID': event['id']
}
airtable_table.create(new_record)
except Exception as e:
print(f"Error in google_calendar_to_airtable: {e}")
def delete_airtable_record_if_calendar_event_deleted():
"""
Deletes Airtable records if corresponding Google Calendar events are deleted.
"""
try:
airtable_table = get_airtable_table()
calendar_service = get_google_calendar_service()
# Fetch all Airtable records with Google Calendar IDs
airtable_records = airtable_table.all()
for record in airtable_records:
event_id = record['fields'].get('Google Calendar ID', '')
if event_id:
try:
calendar_service.events().get(calendarId=CALENDAR_ID, eventId=event_id).execute()
except Exception as e:
# If event not found, delete the Airtable record
if 'Not Found' in str(e):
airtable_table.delete(record['id'])
except Exception as e:
print(f"Error in delete_airtable_record_if_calendar_event_deleted: {e}")
def delete_google_calendar_event_if_airtable_record_deleted():
"""
Deletes Google Calendar events if corresponding Airtable records are deleted.
"""
try:
calendar_service = get_google_calendar_service()
airtable_table = get_airtable_table()
# Fetch all Google Calendar events
now = datetime.datetime.utcnow().isoformat() + 'Z'
events_result = calendar_service.events().list(calendarId=CALENDAR_ID, timeMin=now, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
for event in events:
existing_records = airtable_table.all(formula=f"{{Google Calendar ID}} = \"{event['id']}\"")
if not existing_records:
calendar_service.events().delete(calendarId=CALENDAR_ID, eventId=event['id']).execute()
except Exception as e:
print(f"Error in delete_google_calendar_event_if_airtable_record_deleted: {e}")