建立事件

假設某個應用程式協助使用者找到最佳健行路線。只要將健行計畫新增為日曆活動,使用者就能充分運用系統自動整理行程。Google 日曆可以幫助員工分享計劃並且提醒他們 讓他們隨時做好準備。此外,由於 Google 產品完美整合,Google 即時資訊可以偵測出出發時間,Google 地圖也會將他們準時到達會議地點。

本文說明如何建立日曆活動,以及將這些活動新增至使用者的日曆。

新增活動

如要建立事件,請至少呼叫 events.insert() 方法,並提供下列必要參數:

  • calendarId 是日曆 ID,可以是建立事件的日曆電子郵件地址,也可以是特殊關鍵字 'primary' (會使用登入使用者的主要日曆)。如果您不知道要使用的日曆電子郵件地址,可以在 Google 日曆網頁使用者介面的日曆設定 (位於「日曆網址」部分) 中查看該電子郵件地址,或者可以在 calendarList.list() 呼叫的結果中尋找該日曆。
  • event 是要建立且包含所有必要詳細資料 (例如開始和結束) 的事件。只有兩個必填欄位是 startend 次。如需完整的事件欄位組合,請參閱 event 參考資料

為順利建立事件,您必須:

  • 請將 OAuth 範圍設為 https://www.googleapis.com/auth/calendar,以便您擁有使用者日曆的編輯權限。
  • 確認已驗證的使用者可以使用您提供的 calendarId 來寫入日曆 (例如,針對 calendarId 呼叫 calendarList.get() 並檢查 accessRole)。

新增事件中繼資料

建立日曆活動時,您可以選擇新增活動中繼資料。如果您選擇不在建立期間新增中繼資料,可使用 events.update() 更新多個欄位;但部分欄位 (例如事件 ID) 只能在 events.insert() 作業期間設定。

位置

在地點欄位新增地址即可啟用相關功能,例如:

「出發提醒」或顯示路線指示的地圖。

活動 ID

建立活動時,您可以選擇產生自己的事件 ID

符合我們的格式規定這樣可讓您將本機資料庫中的實體與 Google 日曆中的活動保持同步。而如果作業在日曆後端成功執行後在某些時間點失敗,系統也能避免重複建立活動。如未提供事件 ID,伺服器會為您產生 ID。詳情請參閱事件 ID 參考資料

參與者

您建立的活動會顯示在以下群組的所有主要 Google 日曆中:

納入同一活動 ID 的參與者。如果在插入要求中將 sendNotifications 設為 true,參與者也會收到電子郵件通知。詳情請參閱「多位與會者的事件指南」。

以下範例說明如何建立事件並設定相關中繼資料:

查看

// Refer to the Go quickstart on how to setup the environment:
// https://developers.google.com/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/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/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/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

// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.

$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/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}"

為活動新增雲端硬碟附件

您可以將 Google 雲端硬碟檔案附加在日曆活動中,例如 Google 文件中的會議記錄、Google 試算表的預算、簡報中的簡報,或任何其他相關的 Google 雲端硬碟檔案。您可以在使用 events.insert() 建立事件或之後 (例如使用 events.patch()) 建立事件時新增連結

將 Google 雲端硬碟檔案附加到活動中,有以下兩個部分:

  1. Drive API Files 資源中取得 alternateLink 檔案、titlemimeType 檔案,通常使用 files.get() 方法。
  2. 使用要求主體中設定的 attachments 欄位並將 supportsAttachments 參數設為 true 來建立或更新事件。

以下程式碼範例說明如何更新現有事件以新增附件:

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

在活動中新增視訊會議和電話會議

您可以將活動與 HangoutsGoogle Meet 會議建立關聯,讓使用者透過電話或視訊通話進行遠端會議。

conferenceData 欄位可用來讀取、複製及清除現有會議詳細資料;也可用來要求產生新會議。如要允許建立及修改會議詳細資料,請將 conferenceDataVersion 要求參數設為 1

目前支援三種 conferenceData 類型,如 conferenceData.conferenceSolution.key.type 所示:

  1. Hangouts 消費者版 (eventHangout)
  2. 傳統版 Hangouts Google Workspace 使用者 (已淘汰;eventNamedHangout)
  3. Google Meet (hangoutsMeet)

您可以查看 calendarscalendarList 集合中的 conferenceProperties.allowedConferenceSolutionTypes,瞭解任何指定使用者日曆支援的會議類型。您也可以查看 settings 集合中的 autoAddHangouts 設定,瞭解使用者是否要為所有新建事件建立 Hangouts。

除了 type 以外,conferenceSolution 也提供 nameiconUri 欄位,可用來代表會議解決方案,如下所示:

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

只要為 createRequest 提供一個新產生的 requestId,可以是隨機的 string,為活動建立新會議。會議是非同步建立,但您隨時可以查看要求的狀態,讓使用者瞭解情況。

舉例來說,如要要求為現有活動產生會議,請按照下列步驟操作:

JavaScript

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

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

對這個呼叫的即時回應可能尚未包含完整的 conferenceData;這項資訊會以狀態欄位中的狀態碼 pending 表示。填入會議資訊後,狀態碼會變更為 successentryPoints 欄位包含相關資訊,說明使用者可使用哪些影片和電話 URI 撥入會議。

如果要以相同的會議詳細資料排定多個日曆活動,您可以將整個 conferenceData 從一個活動複製到另一個活動。

在某些情況下,複製功能非常實用。舉例來說,假設您正在開發一個招募應用程式,專門為候選人和參與者設定不同事件;此外,您還想要保護面試者的身分,但又想確保所有參與者加入相同的會議通話。