0Pricing
AI Agents · レッスン

カレンダーイベントの作成と検索

Google Calendar APIで、イベントの一覧表示、会議の作成、リマインダーの設定を行います。

「カレンダーイベントの作成と検索」はCoddyKit上の無料AI Agentsレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Agents学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Agentsコースには全4レッスンが含まれています。

Google Calendar APIの概要

Google Calendar APIでは、エージェントが予定を読み取り、作成、更新、削除できます。Gmailと同じGoogle OAuth認証を使用します。主要なリソースはEventオブジェクトで、予定はCalendarに属します。'primary'カレンダーIDは、認証済みユーザーのメインカレンダーを指します。

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パラメータで時刻範囲を絞り込みます。タイムゾーンオフセット付きの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

予定の開始時刻と終了時刻の解析

Calendarの予定には、時刻を表す形式が2種類あります。通常の予定には、タイムゾーン付きの特定の時刻を表す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形式で指定する必要があります。start/endのtimeZoneフィールドでタイムゾーン名を指定します。

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"]]}')

予定へのリマインダー追加

予定には、開始前に送信される通知であるremindersを設定できます。ブラウザやアプリ内で通知するには'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'])

繰り返し予定の作成

繰り返し予定では、iCalendar RFC 5545と同じ形式のRRULE(繰り返しルール)文字列を使用します。よく使うルールには、月・水・金の予定を表すFREQ=WEEKLY;BYDAY=MO,WE,FRや、毎月第1月曜日の予定を表す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のレスポンスに含まれる予定IDが必要です。

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'を設定すると、参加者に通知されます。繰り返し予定では、使用する予定IDに応じて、1つのインスタンスだけを削除することも、シリーズ全体を削除することもできます。

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

空き時間の確認

会議をスケジュールする前に、freebusy APIを使用して参加者の空き状況を確認してください。この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

クエリによる予定の検索

events().list()のqパラメータを使用すると、テキストで予定を検索できます。検索対象には、タイトル、説明、場所、参加者名が含まれます。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()を使用

よくある質問

「カレンダーイベントの作成と検索」レッスンは無料ですか?

はい。「カレンダーイベントの作成と検索」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Agentsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agentsコースには全4レッスンが含まれています。

「カレンダーイベントの作成と検索」で何を学びますか?

Google Calendar APIで、イベントの一覧表示、会議の作成、リマインダーの設定を行います。 ブラウザで直接実行するハンズオンコードでAI Agentsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Agentsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Agentsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「カレンダーイベントの作成と検索」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Agentsレッスンでコードを書いて実行できますか?

はい。すべてのAI Agentsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. API経由でGmailに接続する
  2. プログラムによるメールの読み取りと送信
  3. カレンダーイベントの作成と検索
  4. シンプルなメールアシスタントエージェントの構築
← AI Agentsに戻る