0Pricing
AI Agents · Lekcja

Tworzenie i wyszukiwanie wydarzeń w kalendarzu

Google Calendar API: listowanie wydarzeń, tworzenie spotkań i ustawianie przypomnień.

Tworzenie i wyszukiwanie wydarzeń w kalendarzu to bezpłatna lekcja AI Agents na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej AI Agents, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs AI Agents zawiera 4 lekcji w sumie.

Przegląd API Google Calendar

Interfejs API Google Calendar umożliwia agentom odczytywanie, tworzenie, aktualizowanie i usuwanie wydarzeń w kalendarzu. Korzysta z tego samego uwierzytelniania Google OAuth co Gmail. Głównym zasobem jest obiekt Event, a wydarzenia należą do elementu Calendar. Identyfikator kalendarza 'primary' odnosi się do głównego kalendarza uwierzytelnionego użytkownika.

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

Wyświetlanie nadchodzących wydarzeń

Należy użyć service.events().list(), aby pobrać wydarzenia. Parametry timeMin i timeMax filtrują wydarzenia według zakresu czasu. Należy zawsze używać ciągów daty i czasu w formacie RFC 3339 z przesunięciem strefy czasowej. Ustawienie singleEvents=True rozwija wydarzenia cykliczne do postaci pojedynczych wystąpień.

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

Analizowanie godzin rozpoczęcia i zakończenia wydarzeń

Wydarzenia w kalendarzu mają dwa typy wartości czasu: dateTime (konkretna godzina wraz ze strefą czasową) w przypadku zwykłych wydarzeń oraz date (sama data, bez godziny) w przypadku wydarzeń całodniowych. Przed analizowaniem należy zawsze sprawdzić, które pole istnieje.

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

Tworzenie prostego wydarzenia

Należy użyć service.events().insert(), aby utworzyć nowe wydarzenie. Minimalny zestaw wymaganych pól obejmuje summary (tytuł), start i end. Godziny muszą być zapisane w formacie RFC 3339 ze strefą czasową. Pole timeZone w sekcjach start/end określa nazwę strefy czasowej.

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')

Dodawanie uczestników do wydarzeń

Uczestników należy dodać do wydarzenia, umieszczając w nim listę attendees zawierającą adresy e-mail. Ustawienie sendUpdates='all' powoduje automatyczne wysłanie zaproszeń Google Calendar do wszystkich uczestników. Wartość 'externalOnly' służy do powiadamiania wyłącznie gości zewnętrznych.

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

Dodawanie przypomnień do wydarzeń

Wydarzenia mogą mieć przypomnienia — powiadomienia wysyłane przed wydarzeniem. Wartość 'popup' służy do powiadomień w przeglądarce lub aplikacji, a 'email' do przypomnień wysyłanych e-mailem. Ustawienie useDefault: False pozwala zastąpić domyślne ustawienia kalendarza własnymi terminami.

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

Tworzenie wydarzeń cyklicznych

Wydarzenia cykliczne korzystają z ciągu RRULE (reguły powtarzania) — tego samego formatu co iCalendar RFC 5545. Typowe reguły to: FREQ=WEEKLY;BYDAY=MO,WE,FR dla poniedziałków, śród i piątków oraz FREQ=MONTHLY;BYDAY=1MO dla pierwszego poniedziałku każdego miesiąca.

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'
)

Aktualizowanie istniejącego wydarzenia

Należy użyć service.events().patch(), aby zaktualizować wybrane pola istniejącego wydarzenia bez zastępowania całego wydarzenia. Metoda .update() zastępuje całą treść wydarzenia. Obie metody wymagają identyfikatora wydarzenia z pierwotnej odpowiedzi create lub 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')

Usuwanie wydarzeń

Należy użyć service.events().delete(), aby anulować i usunąć wydarzenie. Ustawienie sendUpdates='all' powiadamia uczestników. W przypadku wydarzeń cyklicznych można usunąć pojedyncze wystąpienie albo całą serię, zależnie od użytego identyfikatora wydarzenia.

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

Sprawdzanie dostępności w kalendarzu

Przed zaplanowaniem spotkania należy sprawdzić dostępność uczestników za pomocą interfejsu API freebusy. Zwraca on zajęte przedziały czasu dla listy kalendarzy w określonym przedziale czasowym — doskonale nadaje się do wyszukiwania wolnych terminów dla agentów zajmujących się planowaniem.

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

Wyszukiwanie wydarzeń za pomocą zapytania

Parametr q w metodzie events().list() służy do wyszukiwania wydarzeń według tekstu — wyszukiwanie obejmuje tytuł, opis, lokalizację i nazwy uczestników. Połączenie go z parametrami timeMin/timeMax pozwala zawęzić wyniki do określonego okresu.

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

Szybki test: parametr singleEvents

Proszę sprawdzić znajomość interfejsu API Calendar.

Podsumowanie API Calendar

Państwa agenty mogą teraz programowo zarządzać Google Calendar:

  • Wyświetlanie wydarzeń: events().list(timeMin=now, singleEvents=True, orderBy='startTime')
  • Tworzenie wydarzeń: events().insert(body={summary, start, end, attendees})
  • Wydarzenia cykliczne: należy dodać recurrence: ['RRULE:FREQ=WEEKLY;BYDAY=MO']
  • Przypomnienia: należy użyć reminders.overrides z wartościami method: popup/email i minutes
  • Aktualizowanie: events().patch() do częściowych aktualizacji; sendUpdates='all' do powiadamiania uczestników
  • Dostępność: freebusy().query() do sprawdzania dostępności przed zaplanowaniem spotkania

Często zadawane pytania

Czy lekcja „Tworzenie i wyszukiwanie wydarzeń w kalendarzu” jest bezpłatna?

Tak — pełny tekst „Tworzenie i wyszukiwanie wydarzeń w kalendarzu” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu AI Agents, przejdź na CoddyKit PRO. Kurs AI Agents zawiera 4 lekcji w sumie.

Co nauczysz się w „Tworzenie i wyszukiwanie wydarzeń w kalendarzu”?

Google Calendar API: listowanie wydarzeń, tworzenie spotkań i ustawianie przypomnień. Ćwiczysz AI Agents z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć AI Agents?

Nie wymagamy żadnego doświadczenia. AI Agents w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Tworzenie i wyszukiwanie wydarzeń w kalendarzu”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji AI Agents?

Tak. Każda lekcja AI Agents zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Łączenie z Gmailem przez API
  2. Programowe odczytywanie i wysyłanie e-maili
  3. Tworzenie i wyszukiwanie wydarzeń w kalendarzu
  4. Tworzenie prostego agenta asystenta e-mail
← Powrót do AI Agents