การสร้างและค้นหาเหตุการณ์ในปฏิทิน
Google Calendar API: แสดงรายการเหตุการณ์ สร้างการประชุม และตั้งการแจ้งเตือน
การสร้างและค้นหาเหตุการณ์ในปฏิทิน เป็นบทเรียน AI Agents ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
ภาพรวม Google Calendar API
Google Calendar API ช่วยให้เอเจนต์อ่าน สร้าง อัปเดต และลบกิจกรรมในปฏิทินได้ โดยใช้การตรวจสอบสิทธิ์ Google OAuth แบบเดียวกับ Gmail ทรัพยากรหลักคือออบเจ็กต์ กิจกรรม และกิจกรรมต่าง ๆ จะอยู่ใน ปฏิทิน รหัสปฏิทิน 'primary' หมายถึงปฏิทินหลักของผู้ใช้ที่ผ่านการตรวจสอบสิทธิ์แล้ว
from googleapiclient.discovery import build
# Build calendar service (same credentials as Gmail)
calendar = build(
'calendar', 'v3',
credentials=creds,
cache_discovery=False
)
# Get a list of the user's calendars
cal_list = calendar.calendarList().list().execute()
for cal in cal_list.get('items', []):
print(f'{cal["summary"]}: {cal["id"]}')
# Primary calendar ID is the user's email addressการแสดงรายการกิจกรรมที่กำลังจะมาถึง
ใช้ service.events().list() เพื่อดึงข้อมูลกิจกรรม พารามิเตอร์ timeMin และ timeMax ใช้กรองตามช่วงเวลา ควรใช้สตริง datetime รูปแบบ RFC 3339 ที่มีออฟเซ็ตเขตเวลาเสมอ ตั้งค่า singleEvents=True เพื่อขยายกิจกรรมที่เกิดซ้ำให้เป็นอินสแตนซ์แยกกัน
import datetime
import pytz
def get_upcoming_events(service, calendar_id='primary', max_results=10):
now = datetime.datetime.now(pytz.utc)
time_min = now.isoformat() # RFC 3339 format
time_max = (now + datetime.timedelta(days=7)).isoformat()
events_result = service.events().list(
calendarId=calendar_id,
timeMin=time_min,
timeMax=time_max,
maxResults=max_results,
singleEvents=True, # expand recurring events
orderBy='startTime'
).execute()
events = events_result.get('items', [])
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(f'{start}: {event["summary"]}')
return eventsการแยกวิเคราะห์เวลาเริ่มต้นและสิ้นสุดของกิจกรรม
กิจกรรมในปฏิทินมีเวลาอยู่สองประเภท ได้แก่ dateTime ซึ่งเป็นเวลาเฉพาะพร้อมเขตเวลาสำหรับกิจกรรมทั่วไป และ date ซึ่งเป็นวันที่เท่านั้นโดยไม่มีเวลาสำหรับกิจกรรมตลอดทั้งวัน ควรตรวจสอบก่อนเสมอว่ามีฟิลด์ใดอยู่ จากนั้นจึงแยกวิเคราะห์
from datetime import datetime
import re
def parse_event_time(time_dict):
if 'dateTime' in time_dict:
# Parse RFC 3339 datetime: '2026-05-29T14:00:00+03:00'
dt_str = time_dict['dateTime']
# Python 3.7+ fromisoformat handles this
return datetime.fromisoformat(dt_str), False # not all-day
else:
# All-day event: '2026-05-29'
date_str = time_dict['date']
return datetime.strptime(date_str, '%Y-%m-%d'), True # all-day
for event in events:
start_dt, is_all_day = parse_event_time(event['start'])
end_dt, _ = parse_event_time(event['end'])
duration = end_dt - start_dt if not is_all_day else None
print(f'{event["summary"]}: {start_dt.strftime("%H:%M")} '
f'({"all-day" if is_all_day else str(duration)})')การสร้างกิจกรรมแบบง่าย
ใช้ service.events().insert() เพื่อสร้างกิจกรรมใหม่ ฟิลด์ขั้นต่ำที่จำเป็นคือ summary (ชื่อเรื่อง) start และ end เวลาต้องอยู่ในรูปแบบ RFC 3339 และต้องระบุเขตเวลา ฟิลด์ timeZone ใน start/end ใช้ระบุชื่อเขตเวลา
def create_event(service, title, start_datetime, end_datetime,
description='', timezone='UTC', calendar_id='primary'):
event = {
'summary': title,
'description': description,
'start': {
'dateTime': start_datetime.isoformat(),
'timeZone': timezone
},
'end': {
'dateTime': end_datetime.isoformat(),
'timeZone': timezone
}
}
created = service.events().insert(
calendarId=calendar_id,
body=event
).execute()
print(f'Event created: {created["summary"]}')
print(f'Event ID: {created["id"]}')
print(f'Link: {created["htmlLink"]}')
return created
# --- demo: minimal stand-in for the Calendar API's service object ---
import datetime
class _Exec:
def __init__(self, result):
self._result = result
def execute(self):
return self._result
class _FakeEvents:
def insert(self, calendarId, body):
return _Exec({**body, 'id': 'evt_123',
'htmlLink': 'https://calendar.google.com/event?eid=evt_123'})
class _FakeService:
def events(self):
return _FakeEvents()
service = _FakeService()
start = datetime.datetime(2026, 8, 10, 9, 0)
end = start + datetime.timedelta(hours=1)
create_event(service, 'Team Sync', start, end, description='Weekly sync')
การเพิ่มผู้เข้าร่วมในกิจกรรม
เพิ่มผู้เข้าร่วมในกิจกรรมโดยใส่รายการ attendees พร้อมที่อยู่อีเมล ตั้งค่า sendUpdates='all' เพื่อส่งคำเชิญ Google Calendar ให้ผู้เข้าร่วมทั้งหมดโดยอัตโนมัติ ใช้ 'externalOnly' เพื่อแจ้งเฉพาะผู้เข้าร่วมภายนอก
import datetime
def schedule_meeting(service, title, start_iso, duration_minutes,
attendees, description=''):
start = datetime.datetime.fromisoformat(start_iso)
end = start + datetime.timedelta(minutes=duration_minutes)
event = {
'summary': title,
'description': description,
'start': {'dateTime': start.isoformat(), 'timeZone': 'UTC'},
'end': {'dateTime': end.isoformat(), 'timeZone': 'UTC'},
'attendees': [
{'email': email} for email in attendees
],
'conferenceData': {
'createRequest': {'requestId': f'meet-{start.timestamp()}'}
} # creates a Google Meet link
}
created = service.events().insert(
calendarId='primary',
body=event,
sendUpdates='all', # send invites
conferenceDataVersion=1 # enable Meet link creation
).execute()
return created
# --- demo: minimal stand-in for the Calendar API's service object ---
class _Exec:
def __init__(self, result):
self._result = result
def execute(self):
return self._result
class _FakeEvents:
def insert(self, calendarId, body, sendUpdates=None, conferenceDataVersion=None):
return _Exec({**body, 'id': 'evt_456'})
class _FakeService:
def events(self):
return _FakeEvents()
service = _FakeService()
created = schedule_meeting(
service, 'Sprint Planning', '2026-08-11T10:00:00', 30,
attendees=['alice@example.com', 'bob@example.com']
)
print(f'Meeting scheduled: {created["summary"]}')
print(f'Attendees: {[a["email"] for a in created["attendees"]]}')
การเพิ่มการแจ้งเตือนในกิจกรรม
กิจกรรมสามารถมีการแจ้งเตือน ซึ่งเป็นการแจ้งที่ส่งก่อนเริ่มกิจกรรมได้ ใช้ 'popup' สำหรับการแจ้งเตือนในเบราว์เซอร์หรือแอป และใช้ 'email' สำหรับการแจ้งเตือนทางอีเมล ตั้งค่า useDefault: False เพื่อแทนที่ค่าเริ่มต้นของปฏิทินด้วยช่วงเวลาที่กำหนดเอง
def create_event_with_reminders(service, title, start_iso, end_iso):
event = {
'summary': title,
'start': {'dateTime': start_iso, 'timeZone': 'UTC'},
'end': {'dateTime': end_iso, 'timeZone': 'UTC'},
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60}, # 1 day before
{'method': 'popup', 'minutes': 30}, # 30 min before
{'method': 'popup', 'minutes': 10} # 10 min before
]
}
}
return service.events().insert(
calendarId='primary',
body=event
).execute()
# --- demo: minimal stand-in for the Calendar API's service object ---
class _Exec:
def __init__(self, result):
self._result = result
def execute(self):
return self._result
class _FakeEvents:
def insert(self, calendarId, body):
return _Exec({**body, 'id': 'evt_789'})
class _FakeService:
def events(self):
return _FakeEvents()
service = _FakeService()
created = create_event_with_reminders(
service, 'Deploy Review', '2026-08-12T15:00:00', '2026-08-12T15:30:00'
)
print(f'Event id: {created["id"]}')
print('Reminders:', created['reminders']['overrides'])
การสร้างกิจกรรมที่เกิดซ้ำ
กิจกรรมที่เกิดซ้ำใช้สตริง RRULE (กฎการเกิดซ้ำ) ซึ่งเป็นรูปแบบเดียวกับ iCalendar RFC 5545 กฎที่ใช้บ่อย ได้แก่ FREQ=WEEKLY;BYDAY=MO,WE,FR สำหรับวันจันทร์ พุธ และศุกร์ และ FREQ=MONTHLY;BYDAY=1MO สำหรับวันจันทร์แรกของแต่ละเดือน
def create_recurring_event(service, title, start_iso, end_iso,
rrule, timezone='UTC'):
event = {
'summary': title,
'start': {'dateTime': start_iso, 'timeZone': timezone},
'end': {'dateTime': end_iso, 'timeZone': timezone},
'recurrence': [
f'RRULE:{rrule}' # recurrence rule string
]
}
return service.events().insert(
calendarId='primary',
body=event
).execute()
# Weekly team standup every Monday at 9am for 30 min
create_recurring_event(
service=calendar_service,
title='Team Standup',
start_iso='2026-06-01T09:00:00',
end_iso='2026-06-01T09:30:00',
rrule='FREQ=WEEKLY;BYDAY=MO;COUNT=52', # 52 weeks
timezone='America/New_York'
)การอัปเดตกิจกรรมที่มีอยู่
ใช้ service.events().patch() เพื่ออัปเดตเฉพาะฟิลด์ของกิจกรรมที่มีอยู่โดยไม่ต้องแทนที่กิจกรรมทั้งหมด ใช้ .update() เพื่อแทนที่เนื้อหาของกิจกรรมทั้งหมด ทั้งสองวิธีต้องใช้รหัสกิจกรรมจากการตอบกลับของ create หรือ list เดิม
def reschedule_event(service, event_id, new_start_iso, new_end_iso,
timezone='UTC', calendar_id='primary'):
updated_fields = {
'start': {'dateTime': new_start_iso, 'timeZone': timezone},
'end': {'dateTime': new_end_iso, 'timeZone': timezone}
}
updated_event = service.events().patch(
calendarId=calendar_id,
eventId=event_id,
body=updated_fields,
sendUpdates='all' # notify attendees of the change
).execute()
print(f'Event rescheduled: {updated_event["summary"]}')
print(f'New start: {updated_event["start"]["dateTime"]}')
return updated_event
# --- demo: minimal stand-in for the Calendar API's service object ---
class _Exec:
def __init__(self, result):
self._result = result
def execute(self):
return self._result
class _FakeEvents:
def patch(self, calendarId, eventId, body, sendUpdates=None):
return _Exec({'summary': 'Team Sync', 'id': eventId, **body})
class _FakeService:
def events(self):
return _FakeEvents()
service = _FakeService()
reschedule_event(service, 'evt_123', '2026-08-13T09:00:00', '2026-08-13T10:00:00')
การลบกิจกรรม
ใช้ service.events().delete() เพื่อยกเลิกและนำกิจกรรมออก การตั้งค่า sendUpdates='all' จะแจ้งให้ผู้เข้าร่วมทราบ สำหรับกิจกรรมที่เกิดซ้ำ คุณสามารถลบอินสแตนซ์เดียวหรือลบทั้งชุดได้ ขึ้นอยู่กับรหัสกิจกรรมที่ใช้
from googleapiclient.errors import HttpError
def cancel_event(service, event_id, notify_attendees=True,
calendar_id='primary'):
try:
service.events().delete(
calendarId=calendar_id,
eventId=event_id,
sendUpdates='all' if notify_attendees else 'none'
).execute()
print(f'Event {event_id} cancelled')
return True
except HttpError as e:
if e.resp.status == 404:
print(f'Event {event_id} not found (already deleted?)')
elif e.resp.status == 403:
print('No permission to delete this event')
else:
print(f'Delete failed: {e.resp.status}')
return Falseการตรวจสอบเวลาว่าง/ไม่ว่าง
ก่อนจัดกำหนดการประชุม ให้ตรวจสอบเวลาว่างของผู้เข้าร่วมโดยใช้ API freebusy API นี้จะแสดงช่วงเวลาที่ไม่ว่างของปฏิทินในรายการตามช่วงเวลาที่กำหนด จึงเหมาะอย่างยิ่งสำหรับการค้นหาช่วงเวลาว่างให้เอเจนต์จัดกำหนดการ
import datetime
import pytz
def check_availability(service, attendees, duration_hours=1):
now = datetime.datetime.now(pytz.utc)
time_min = now.isoformat()
time_max = (now + datetime.timedelta(days=5)).isoformat()
body = {
'timeMin': time_min,
'timeMax': time_max,
'timeZone': 'UTC',
'items': [{'id': email} for email in attendees]
}
result = service.freebusy().query(body=body).execute()
for email in attendees:
busy_slots = result['calendars'].get(email, {}).get('busy', [])
print(f'{email}: {len(busy_slots)} busy slots in next 5 days')
for slot in busy_slots[:3]:
print(f' Busy: {slot["start"]} -> {slot["end"]}')
return resultการค้นหากิจกรรมด้วยคำค้น
ใช้พารามิเตอร์ q ใน events().list() เพื่อค้นหากิจกรรมด้วยข้อความ โดยค้นหาจากชื่อเรื่อง คำอธิบาย สถานที่ และชื่อผู้เข้าร่วม ใช้ร่วมกับ timeMin/timeMax เพื่อจำกัดผลลัพธ์ให้อยู่ในช่วงเวลาที่กำหนด
def search_events(service, query, days_back=30, days_forward=30,
calendar_id='primary'):
import datetime, pytz
now = datetime.datetime.now(pytz.utc)
result = service.events().list(
calendarId=calendar_id,
q=query,
timeMin=(now - datetime.timedelta(days=days_back)).isoformat(),
timeMax=(now + datetime.timedelta(days=days_forward)).isoformat(),
singleEvents=True,
orderBy='startTime',
maxResults=50
).execute()
events = result.get('items', [])
print(f'Found {len(events)} events matching "{query}"')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(f' {start}: {event["summary"]}')
return eventsตรวจสอบความเข้าใจอย่างรวดเร็ว: พารามิเตอร์ singleEvents
ทดสอบความเข้าใจเกี่ยวกับ Calendar API
สรุป Calendar API
ขณะนี้เอเจนต์ของคุณสามารถจัดการ Google Calendar ด้วยโปรแกรมได้แล้ว:
- แสดงรายการกิจกรรม:
events().list(timeMin=now, singleEvents=True, orderBy='startTime') - สร้างกิจกรรม:
events().insert(body={summary, start, end, attendees}) - กิจกรรมที่เกิดซ้ำ: เพิ่ม
recurrence: ['RRULE:FREQ=WEEKLY;BYDAY=MO'] - การแจ้งเตือน: ใช้
reminders.overridesพร้อมmethod: popup/emailและminutes - อัปเดต: ใช้
events().patch()สำหรับการอัปเดตบางส่วน และใช้sendUpdates='all'เพื่อแจ้งผู้เข้าร่วม - เวลาว่าง/ไม่ว่าง: ใช้
freebusy().query()เพื่อตรวจสอบเวลาว่างก่อนจัดกำหนดการ
คำถามที่พบบ่อย
บทเรียน “การสร้างและค้นหาเหตุการณ์ในปฏิทิน” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การสร้างและค้นหาเหตุการณ์ในปฏิทิน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างและค้นหาเหตุการณ์ในปฏิทิน”
Google Calendar API: แสดงรายการเหตุการณ์ สร้างการประชุม และตั้งการแจ้งเตือน คุณปฏิบัติ AI Agents ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างและค้นหาเหตุการณ์ในปฏิทิน” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents นี้ได้ไหม
ได้ บทเรียน AI Agents ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเชื่อมต่อ Gmail ผ่าน API
- การอ่านและส่งอีเมลด้วยโปรแกรม
- การสร้างและค้นหาเหตุการณ์ในปฏิทิน
- การสร้างตัวแทนผู้ช่วยอีเมลอย่างง่าย