假設有款應用程式可協助使用者尋找最佳健行路線。將健行計畫新增為日曆活動,系統就會自動協助使用者保持井然有序。Google 日曆可協助他們分享計畫並提醒相關事宜,讓他們能輕鬆準備。此外,由於 Google 產品可完美整合,Google 地圖會準時將他們帶往會合地點。
本文說明如何建立日曆活動,並新增至使用者的日曆。
新增活動
如要建立事件,請呼叫 events.insert 方法,並提供至少下列參數:
calendarId是日曆 ID,可以是建立活動的日曆電子郵件地址,也可以是特殊關鍵字'primary',後者會使用登入使用者的主要日曆。如果您不知道要使用的日曆電子郵件地址,可以在日曆網頁使用者介面的日曆設定中查看 (位於「日曆地址」部分),也可以在calendarList.list呼叫的結果中尋找。event是要建立的活動,請提供所有必要詳細資料,例如開始和結束時間。只有start和end時間是必填欄位。如需完整的事件欄位集,請參閱Events資源參考資料。
如要建立活動,請按照下列步驟操作:
- 將 OAuth 範圍設為
https://www.googleapis.com/auth/calendar,即可取得使用者的日曆編輯權限。 - 請確認已驗證的使用者具有您提供的
calendarId日曆寫入權限 (例如呼叫calendarList.get取得calendarId,並檢查accessRole)。
新增事件中繼資料
建立日曆活動時,您可以選擇性地新增活動中繼資料。如果您選擇在建立時不新增中繼資料,可以使用 events.update 方法更新許多欄位;不過,部分欄位 (例如活動 ID) 只能在 events.insert 作業期間設定。
- 位置
- 在「地點」欄位中新增地址,即可啟用「出發時間」等功能,或顯示附有路線的地圖。
- 事件 ID
- 建立活動時,您可以選擇自行產生符合格式規定的活動 ID。這樣一來,您就能讓本機資料庫中的實體與 Google 日曆中的活動保持同步。如果作業在日曆後端成功執行後失敗,這項功能也能避免重複建立活動。如果未提供事件 ID,伺服器會自動產生。詳情請參閱事件 ID 參考資料。
- 參與者
- 您建立的活動會顯示在所有主要日曆中,並與您加入的參與者共用相同的活動 ID。如果您在插入要求中設定
sendUpdates為"all"或"externalOnly",相關出席者就會收到活動的電子郵件通知。如要瞭解詳情,請參閱有多位參與者的活動。
下列範例示範如何建立事件及設定中繼資料:
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'))
小茹
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 Drive API 檔案資源取得檔案
alternateLinkURL、title和mimeType,通常是使用files.get方法。 - 在要求主體中設定
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()
在活動中新增視訊和電話會議
您可以將活動與 Google Meet 會議建立關聯,讓使用者透過電話或視訊通話進行遠端會議。
您可以使用「conferenceData」欄位讀取、複製及清除現有的會議詳細資料,或要求產生新的會議。如要允許建立及修改會議詳細資料,請將 conferenceDataVersion 要求參數設為 1。
系統支援下列會議類型 (以 conferenceData.conferenceSolution.key.type 表示):
- Google Meet (
hangoutsMeet)
如要瞭解特定使用者日曆支援的會議類型,請查看 calendars 和 calendarList 集合中的 conferenceProperties.allowedConferenceSolutionTypes。
除了 type,conferenceSolution 也提供 name 和 iconUri 欄位,可用於代表會議解決方案,如下所示:
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 做為隨機字串。會議是以非同步方式建立,但您隨時可以查看要求狀態,讓使用者瞭解情況。
舉例來說,如要為現有活動要求產生會議,請執行下列操作:
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);
});
這項呼叫的即時回應可能尚未包含完整填入的 conferenceData;status 欄位包含 pending。會議資訊填入後,狀態碼會變更為 success。entryPoints 欄位包含使用者可撥入的影片和電話 URI 相關資訊。
如要安排多個具有相同會議詳細資料的 Google 日曆活動,可以將一個活動的整個 conferenceData 複製到另一個活動。
在某些情況下,複製功能非常實用。舉例來說,假設您正在開發招募應用程式,並為應徵者和面試官分別設定活動,您想保護面試官的身分,但也要確保所有參與者加入同一場電話會議。