import os
import requests
import json
from datetime import datetime
def get_event_types(api_key):
"""Fetches available event types from the Cal.com API."""
print("\nFetching available event types...")
url = f"https://api.cal.com/v1/event-types?apiKey={api_key}"
try:
response = requests.get(url)
response.raise_for_status()
return response.json().get("event_types", [])
except requests.exceptions.RequestException as e:
print(f"❌ Error fetching event types: {e}")
return None
def create_cal_appointment(api_key, start_time, event_type_id, user_id, time_zone, attendee_name, attendee_email):
"""
Creates a new appointment in Cal.com.
"""
if not api_key:
print("Error: CALCOM_API_KEY not found in environment variables.")
return None
url = f"https://api.cal.com/v1/bookings?apiKey={api_key}"
booking_data = {
"start": start_time.isoformat() + "Z",
"eventTypeId": event_type_id,
"responses": {
"name": attendee_name,
"email": attendee_email,
},
"timeZone": time_zone,
"language": "en",
"userId": user_id,
"status": "ACCEPTED",
"metadata": {}
}
headers = {
"Content-Type": "application/json"
}
try:
response = requests.post(url, headers=headers, data=json.dumps(booking_data))
response.raise_for_status()
print("\n✅ Successfully created appointment:")
booking_data = response.json()
if booking_data:
title = booking_data.get('title')
start_time_str = booking_data.get('startTime')
uid = booking_data.get('uid')
print(f" Who: {title if title else 'N/A'}")
if start_time_str:
when = datetime.fromisoformat(start_time_str[:-1]).strftime('%A, %b %d at %I:%M %p')
print(f" When: {when}")
else:
print(" When: N/A")
print(f" UID: {uid if uid else 'N/A'}")
else:
print(" (Could not parse booking details, printing raw response)")
print(json.dumps(response.json(), indent=2))
return booking_data
except requests.exceptions.RequestException as e:
print(f"\n❌ Error creating appointment: {e}")
if e.response is not None:
print(f"Response status code: {e.response.status_code}")
try:
print(f"Response JSON: {e.response.json()}")
except json.JSONDecodeError:
print(f"Response text: {e.response.text}")
return None
def get_user_input(api_key):
"""Gathers appointment details from the user."""
print("--- Create a New Cal.com Appointment ---")
event_types_list = get_event_types(api_key)
if not event_types_list:
print("Could not retrieve event types. Exiting.")
return None
event_types = {
str(i + 1): {
"id": event["id"],
"title": event["title"],
"duration": event["length"]
}
for i, event in enumerate(event_types_list)
}
print("\nPlease select an event type:")
for key, event in event_types.items():
print(f" {key}: {event['title']} ({event['duration']} mins)")
choice = input(f"Enter choice (1-{len(event_types)}): ")
selected_event = event_types.get(choice)
while not selected_event:
print("❌ Invalid choice, please try again.")
choice = input(f"Enter choice (1-{len(event_types)}): ")
selected_event = event_types.get(choice)
attendee_name = input("Enter attendee's full name: ")
attendee_email = input("Enter attendee's email: ")
while True:
date_str = input("Enter appointment date (YYYY-MM-DD): ")
time_str = input("Enter appointment time (HH:MM, 24-hour format): ")
try:
start_time = datetime.strptime(f"{date_str} {time_str}", "%Y-%m-%d %H:%M")
break
except ValueError:
print("❌ Invalid date or time format. Please try again.")
return {
"event_type_id": selected_event["id"],
"attendee_name": attendee_name,
"attendee_email": attendee_email,
"start_time": start_time,
}
if __name__ == "__main__":
cal_api_key = os.getenv("CALCOM_API_KEY")
if not cal_api_key:
print("Error: CALCOM_API_KEY environment variable not set.")
try:
from dotenv import load_dotenv
load_dotenv()
cal_api_key = os.getenv("CALCOM_API_KEY")
if not cal_api_key:
raise ValueError()
except (ImportError, ValueError):
print("Could not load .env file. Please ensure it exists or the variable is set.")
exit(1)
target_user_id = 1591474
target_time_zone = "America/New_York"
params = get_user_input(cal_api_key)
if params:
create_cal_appointment(
cal_api_key,
params["start_time"],
params["event_type_id"],
target_user_id,
target_time_zone,
params["attendee_name"],
params["attendee_email"]
)