Tworzenie zdarzeń

Wyobraź sobie aplikację, która pomaga użytkownikom znaleźć najlepsze trasy piesze. Dodając plan wędrówki jako wydarzenie w kalendarzu, użytkownicy otrzymują dużą pomoc w automatycznym utrzymywaniu porządku. Kalendarz Google pomaga im udostępnić plan i przypomina o nim, dzięki czemu mogą się przygotować bez stresu. Dzięki płynnej integracji usług Google, Google Now przypomina im o godzinie wyjazdu, a Mapy Google prowadzą ich na miejsce spotkania.

Z tego artykułu dowiesz się, jak tworzyć wydarzenia w kalendarzu i dodawać je do kalendarzy użytkowników.

Dodaj wydarzenie

Aby utworzyć zdarzenie, wywołaj metodę events.insert(), podając co najmniej te parametry:

  • calendarId to identyfikator kalendarza, który może być adresem e-mail kalendarza, w którym ma zostać utworzone wydarzenie, lub specjalnym słowem kluczowym 'primary', które będzie używać kalendarza głównego zalogowanego użytkownika. Jeśli nie znasz adresu e-mail kalendarza, którego chcesz użyć, możesz go sprawdzić w ustawieniach kalendarza w interfejsie internetowym Kalendarza Google (w sekcji „Adres kalendarza”) lub wyszukać go w wyniku wywołania calendarList.list().
  • event to wydarzenie, które chcesz utworzyć, zawierające wszystkie niezbędne szczegóły, takie jak godzina rozpoczęcia i zakończenia. Jedynymi wymaganymi polami są start i end. Pełny zestaw pól zdarzeń znajdziesz w dokumentacji event.

Aby utworzyć wydarzenia, musisz:

  • Ustaw zakres OAuth na https://www.googleapis.com/auth/calendar, aby mieć uprawnienia do edycji kalendarza użytkownika.
  • Upewnij się, że uwierzytelniony użytkownik ma uprawnienia do zapisu w kalendarzu o podanym identyfikatorze calendarId (np. wywołując metodę calendarList.get() dla identyfikatora calendarId i sprawdzając accessRole).

Dodaj metadane zdarzenia

Podczas tworzenia wydarzenia w kalendarzu możesz opcjonalnie dodać metadane wydarzenia. Jeśli nie zdecydujesz się na dodanie metadanych podczas tworzenia, możesz zaktualizować wiele pól za pomocą metody events.update(). Niektóre pola, takie jak identyfikator zdarzenia, można jednak ustawić tylko podczas operacji events.insert().

Lokalizacja
Dodanie adresu w polu lokalizacji umożliwia korzystanie z funkcji takich jak „godzina wyjazdu” czy wyświetlanie mapy ze wskazówkami dojazdu.
Identyfikator zdarzenia
Podczas tworzenia wydarzenia możesz wygenerować własny identyfikator wydarzenia, który spełnia nasze wymagania dotyczące formatu. Dzięki temu możesz synchronizować encje w lokalnej bazie danych z wydarzeniami w Kalendarzu Google. Zapobiega to też tworzeniu zduplikowanych wydarzeń, jeśli operacja nie powiedzie się w pewnym momencie po jej pomyślnym wykonaniu w backendzie Kalendarza. Jeśli nie podasz identyfikatora zdarzenia, serwer wygeneruje go za Ciebie. Więcej informacji znajdziesz w dokumentacji dotyczącej identyfikatorów zdarzeń.
Uczestnicy
Utworzone wydarzenie pojawi się we wszystkich kalendarzach głównych uczestników, których dodano z tym samym identyfikatorem wydarzenia. Domyślnie (sendUpdates="externalOnly") Kalendarz wysyła e-maile z powiadomieniami tylko do uczestników, którzy nie korzystają z Kalendarza Google. Ustaw sendUpdates na "all", aby powiadomić wszystkich uczestników, lub na "none", aby nie wysyłać powiadomień e-mailem. Więcej informacji znajdziesz w artykule o wydarzeniach z wieloma uczestnikami.

Poniższe przykłady pokazują, jak utworzyć zdarzenie i ustawić jego metadane:

Go

// Refer to the Go quickstart on how to setup the environment:
// https://developers.google.com/workspace/calendar/quickstart/go
// Change the scope to calendar.CalendarScope and delete any stored credentials.

event := &calendar.Event{
  Summary: "Google I/O 2015",
  Location: "800 Howard St., San Francisco, CA 94103",
  Description: "A chance to hear more about Google's developer products.",
  Start: &calendar.EventDateTime{
    DateTime: "2015-05-28T09:00:00-07:00",
    TimeZone: "America/Los_Angeles",
  },
  End: &calendar.EventDateTime{
    DateTime: "2015-05-28T17:00:00-07:00",
    TimeZone: "America/Los_Angeles",
  },
  Recurrence: []string{"RRULE:FREQ=DAILY;COUNT=2"},
  Attendees: []*calendar.EventAttendee{
    &calendar.EventAttendee{Email:"lpage@example.com"},
    &calendar.EventAttendee{Email:"sbrin@example.com"},
  },
}

calendarId := "primary"
event, err = srv.Events.Insert(calendarId, event).Do()
if err != nil {
  log.Fatalf("Unable to create event. %v\n", err)
}
fmt.Printf("Event created: %s\n", event.HtmlLink)

Java

// Refer to the Java quickstart on how to setup the environment:
// https://developers.google.com/workspace/calendar/quickstart/java
// Change the scope to CalendarScopes.CALENDAR and delete any stored
// credentials.

Event event = new Event()
    .setSummary("Google I/O 2015")
    .setLocation("800 Howard St., San Francisco, CA 94103")
    .setDescription("A chance to hear more about Google's developer products.");

DateTime startDateTime = new DateTime("2015-05-28T09:00:00-07:00");
EventDateTime start = new EventDateTime()
    .setDateTime(startDateTime)
    .setTimeZone("America/Los_Angeles");
event.setStart(start);

DateTime endDateTime = new DateTime("2015-05-28T17:00:00-07:00");
EventDateTime end = new EventDateTime()
    .setDateTime(endDateTime)
    .setTimeZone("America/Los_Angeles");
event.setEnd(end);

String[] recurrence = new String[] {"RRULE:FREQ=DAILY;COUNT=2"};
event.setRecurrence(Arrays.asList(recurrence));

EventAttendee[] attendees = new EventAttendee[] {
    new EventAttendee().setEmail("lpage@example.com"),
    new EventAttendee().setEmail("sbrin@example.com"),
};
event.setAttendees(Arrays.asList(attendees));

EventReminder[] reminderOverrides = new EventReminder[] {
    new EventReminder().setMethod("email").setMinutes(24 * 60),
    new EventReminder().setMethod("popup").setMinutes(10),
};
Event.Reminders reminders = new Event.Reminders()
    .setUseDefault(false)
    .setOverrides(Arrays.asList(reminderOverrides));
event.setReminders(reminders);

String calendarId = "primary";
event = service.events().insert(calendarId, event).execute();
System.out.printf("Event created: %s\n", event.getHtmlLink());

JavaScript

// Refer to the JavaScript quickstart on how to setup the environment:
// https://developers.google.com/workspace/calendar/quickstart/js
// Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
// stored credentials.

const event = {
  'summary': 'Google I/O 2015',
  'location': '800 Howard St., San Francisco, CA 94103',
  'description': 'A chance to hear more about Google\'s developer products.',
  'start': {
    'dateTime': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles'
  },
  'end': {
    'dateTime': '2015-05-28T17:00:00-07:00',
    'timeZone': 'America/Los_Angeles'
  },
  'recurrence': [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  'attendees': [
    {'email': 'lpage@example.com'},
    {'email': 'sbrin@example.com'}
  ],
  'reminders': {
    'useDefault': false,
    'overrides': [
      {'method': 'email', 'minutes': 24 * 60},
      {'method': 'popup', 'minutes': 10}
    ]
  }
};

const request = gapi.client.calendar.events.insert({
  'calendarId': 'primary',
  'resource': event
});

request.execute(function(event) {
  appendPre('Event created: ' + event.htmlLink);
});

Node.js

// Refer to the Node.js quickstart on how to setup the environment:
// https://developers.google.com/workspace/calendar/quickstart/node
// Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
// stored credentials.

const event = {
  'summary': 'Google I/O 2015',
  'location': '800 Howard St., San Francisco, CA 94103',
  'description': 'A chance to hear more about Google\'s developer products.',
  'start': {
    'dateTime': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'end': {
    'dateTime': '2015-05-28T17:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'recurrence': [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  'attendees': [
    {'email': 'lpage@example.com'},
    {'email': 'sbrin@example.com'},
  ],
  'reminders': {
    'useDefault': false,
    'overrides': [
      {'method': 'email', 'minutes': 24 * 60},
      {'method': 'popup', 'minutes': 10},
    ],
  },
};

calendar.events.insert({
  auth: auth,
  calendarId: 'primary',
  resource: event,
}, function(err, event) {
  if (err) {
    console.log('There was an error contacting the Calendar service: ' + err);
    return;
  }
  console.log('Event created: %s', event.htmlLink);
});

PHP

$event = new Google_Service_Calendar_Event(array(
  'summary' => 'Google I/O 2015',
  'location' => '800 Howard St., San Francisco, CA 94103',
  'description' => 'A chance to hear more about Google\'s developer products.',
  'start' => array(
    'dateTime' => '2015-05-28T09:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'end' => array(
    'dateTime' => '2015-05-28T17:00:00-07:00',
    'timeZone' => 'America/Los_Angeles',
  ),
  'recurrence' => array(
    'RRULE:FREQ=DAILY;COUNT=2'
  ),
  'attendees' => array(
    array('email' => 'lpage@example.com'),
    array('email' => 'sbrin@example.com'),
  ),
  'reminders' => array(
    'useDefault' => FALSE,
    'overrides' => array(
      array('method' => 'email', 'minutes' => 24 * 60),
      array('method' => 'popup', 'minutes' => 10),
    ),
  ),
));

$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);

Python

# Refer to the Python quickstart on how to setup the environment:
# https://developers.google.com/workspace/calendar/quickstart/python
# Change the scope to 'https://www.googleapis.com/auth/calendar' and delete any
# stored credentials.

event = {
  'summary': 'Google I/O 2015',
  'location': '800 Howard St., San Francisco, CA 94103',
  'description': 'A chance to hear more about Google\'s developer products.',
  'start': {
    'dateTime': '2015-05-28T09:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'end': {
    'dateTime': '2015-05-28T17:00:00-07:00',
    'timeZone': 'America/Los_Angeles',
  },
  'recurrence': [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  'attendees': [
    {'email': 'lpage@example.com'},
    {'email': 'sbrin@example.com'},
  ],
  'reminders': {
    'useDefault': False,
    'overrides': [
      {'method': 'email', 'minutes': 24 * 60},
      {'method': 'popup', 'minutes': 10},
    ],
  },
}

event = service.events().insert(calendarId='primary', body=event).execute()
print 'Event created: %s' % (event.get('htmlLink'))

Ruby

event = Google::Apis::CalendarV3::Event.new(
  summary: 'Google I/O 2015',
  location: '800 Howard St., San Francisco, CA 94103',
  description: 'A chance to hear more about Google\'s developer products.',
  start: Google::Apis::CalendarV3::EventDateTime.new(
    date_time: '2015-05-28T09:00:00-07:00',
    time_zone: 'America/Los_Angeles'
  ),
  end: Google::Apis::CalendarV3::EventDateTime.new(
    date_time: '2015-05-28T17:00:00-07:00',
    time_zone: 'America/Los_Angeles'
  ),
  recurrence: [
    'RRULE:FREQ=DAILY;COUNT=2'
  ],
  attendees: [
    Google::Apis::CalendarV3::EventAttendee.new(
      email: 'lpage@example.com'
    ),
    Google::Apis::CalendarV3::EventAttendee.new(
      email: 'sbrin@example.com'
    )
  ],
  reminders: Google::Apis::CalendarV3::Event::Reminders.new(
    use_default: false,
    overrides: [
      Google::Apis::CalendarV3::EventReminder.new(
        reminder_method: 'email',
        minutes: 24 * 60
      ),
      Google::Apis::CalendarV3::EventReminder.new(
        reminder_method: 'popup',
        minutes: 10
      )
    ]
  )
)

result = client.insert_event('primary', event)
puts "Event created: #{result.html_link}"

Dodawanie załączników z Dysku do wydarzeń

Do wydarzeń w kalendarzu możesz dołączać pliki z Dysku Google, takie jak notatki ze spotkania w Dokumentach, budżety w Arkuszach, prezentacje w Prezentacjach lub inne istotne pliki z Dysku Google. Załącznik możesz dodać podczas tworzenia wydarzenia za pomocą metody events.insert() lub później w ramach aktualizacji, np. za pomocą metody events.patch().

Dołączenie pliku z Dysku Google do wydarzenia składa się z 2 części:

  1. Pobierz adres URL pliku alternateLink, title i mimeType z zasobu plików interfejsu Drive API, zwykle za pomocą metody files.get().
  2. Utwórz lub zaktualizuj wydarzenie, ustawiając pola attachments w treści żądania i parametr supportsAttachments na true.

Poniższy przykładowy kod pokazuje, jak zaktualizować istniejące wydarzenie, aby dodać załącznik:

Java

public static void addAttachment(Calendar calendarService, Drive driveService, String calendarId,
    String eventId, String fileId) throws IOException {
  File file = driveService.files().get(fileId).execute();
  Event event = calendarService.events().get(calendarId, eventId).execute();

  List<EventAttachment> attachments = event.getAttachments();
  if (attachments == null) {
    attachments = new ArrayList<EventAttachment>();
  }
  attachments.add(new EventAttachment()
      .setFileUrl(file.getAlternateLink())
      .setMimeType(file.getMimeType())
      .setTitle(file.getTitle()));

  Event changes = new Event()
      .setAttachments(attachments);
  calendarService.events().patch(calendarId, eventId, changes)
      .setSupportsAttachments(true)
      .execute();
}

PHP

function addAttachment($calendarService, $driveService, $calendarId, $eventId, $fileId) {
  $file = $driveService->files->get($fileId);
  $event = $calendarService->events->get($calendarId, $eventId);
  $attachments = $event->attachments;

  $attachments[] = array(
    'fileUrl' => $file->alternateLink,
    'mimeType' => $file->mimeType,
    'title' => $file->title
  );
  $changes = new Google_Service_Calendar_Event(array(
    'attachments' => $attachments
  ));

  $calendarService->events->patch($calendarId, $eventId, $changes, array(
    'supportsAttachments' => TRUE
  ));
}

Python

def add_attachment(calendarService, driveService, calendarId, eventId, fileId):
    file = driveService.files().get(fileId=fileId).execute()
    event = calendarService.events().get(calendarId=calendarId,
                                         eventId=eventId).execute()

    attachments = event.get('attachments', [])
    attachments.append({
        'fileUrl': file['alternateLink'],
        'mimeType': file['mimeType'],
        'title': file['title']
    })

    changes = {
        'attachments': attachments
    }
    calendarService.events().patch(calendarId=calendarId, eventId=eventId,
                                   body=changes,
                                   supportsAttachments=True).execute()

Dodawanie rozmów wideo i telefonicznych do wydarzeń

Możesz powiązać wydarzenia ze spotkaniami w Hangouts i Google Meet, aby umożliwić użytkownikom zdalne spotkania przez połączenie telefoniczne lub rozmowę wideo.

Pole conferenceData może służyć do odczytywania, kopiowania i czyszczenia istniejących szczegółów rozmowy wideo. Można go też używać do generowania nowych rozmów wideo. Aby zezwolić na tworzenie i modyfikowanie szczegółów rozmowy wideo, ustaw parametr żądania conferenceDataVersion na 1.

Obecnie obsługiwane są 3 typy conferenceData, które są oznaczone przez conferenceData.conferenceSolution.key.type:

  1. Hangouts dla użytkowników indywidualnych (eventHangout)
  2. Klasyczna wersja Hangouts dla użytkowników Google Workspace (wycofana; eventNamedHangout)
  3. Google Meet (hangoutsMeet)

Możesz sprawdzić, jaki typ rozmowy wideo jest obsługiwany w danym kalendarzu użytkownika, sprawdzając conferenceProperties.allowedConferenceSolutionTypes w kolekcjach calendars i calendarList. Możesz też sprawdzić, czy użytkownik woli, aby Hangouts były tworzone dla wszystkich nowo utworzonych wydarzeń, sprawdzając ustawienie autoAddHangouts w kolekcji settings.

Oprócz pola type obiekt conferenceSolution zawiera też pola name i iconUri, których możesz użyć do reprezentowania rozwiązania do obsługi rozmów wideo, jak pokazano poniżej:

JavaScript

const solution = event.conferenceData.conferenceSolution;

const content = document.getElementById("content");
const text = document.createTextNode("Join " + solution.name);
const icon = document.createElement("img");
icon.src = solution.iconUri;

content.appendChild(icon);
content.appendChild(text);

Możesz utworzyć nową rozmowę wideo na potrzeby wydarzenia, podając createRequest z nowo wygenerowanym requestId, który może być losowym string. Konferencje są tworzone asynchronicznie, ale zawsze możesz sprawdzić stan żądania, aby poinformować użytkowników o tym, co się dzieje.

Aby na przykład poprosić o wygenerowanie konferencji dla istniejącego wydarzenia:

JavaScript

const eventPatch = {
  conferenceData: {
    createRequest: {requestId: "7qxalsvy0e"}
  }
};

gapi.client.calendar.events.patch({
  calendarId: "primary",
  eventId: "7cbh8rpc10lrc0ckih9tafss99",
  resource: eventPatch,
  sendUpdates: "all",
  conferenceDataVersion: 1
}).execute(function(event) {
  console.log("Conference created for event: %s", event.htmlLink);
});

Bezpośrednia odpowiedź na to wywołanie może nie zawierać jeszcze w pełni wypełnionego pola conferenceData. Wskazuje na to kod stanu pending w polu status. Po wypełnieniu informacji o konferencji kod stanu zmieni się na success. Pole entryPoints zawiera informacje o tym, które identyfikatory URI wideo i telefonu są dostępne dla użytkowników, aby mogli się połączyć.

Jeśli chcesz zaplanować kilka wydarzeń w Kalendarzu z tymi samymi danymi rozmowy wideo, możesz skopiować całe pole conferenceData z jednego wydarzenia do drugiego.

Kopiowanie jest przydatne w określonych sytuacjach. Załóżmy na przykład, że tworzysz aplikację do rekrutacji, która konfiguruje osobne wydarzenia dla kandydata i osoby przeprowadzającej rozmowę kwalifikacyjną. Chcesz chronić tożsamość osoby przeprowadzającej rozmowę, ale chcesz też mieć pewność, że wszyscy uczestnicy dołączą do tego samego połączenia konferencyjnego.