Hãy tưởng tượng một ứng dụng giúp người dùng tìm thấy những tuyến đường đi bộ đường dài tốt nhất. Bằng cách thêm kế hoạch đi bộ đường dài dưới dạng một sự kiện trên lịch, người dùng sẽ nhận được nhiều trợ giúp để tự động sắp xếp. Lịch Google giúp họ chia sẻ kế hoạch và nhắc nhở họ về kế hoạch đó để họ có thể chuẩn bị mà không bị căng thẳng. Ngoài ra, nhờ khả năng tích hợp liền mạch các sản phẩm của Google, Google Now sẽ thông báo cho họ về thời gian cần rời đi và Google Maps sẽ chỉ đường cho họ đến địa điểm họp đúng giờ.
Bài viết này giải thích cách tạo sự kiện trên lịch và thêm sự kiện đó vào lịch của người dùng.
Thêm sự kiện
Để tạo một sự kiện, hãy gọi phương thức events.insert()
bằng cách cung cấp ít nhất các thông số sau:
calendarId
là mã nhận dạng lịch và có thể là địa chỉ email của lịch mà bạn muốn tạo sự kiện hoặc một từ khoá đặc biệt'primary'
. Từ khoá này sẽ sử dụng lịch chính của người dùng đã đăng nhập. Nếu không biết địa chỉ email của lịch mà bạn muốn sử dụng, bạn có thể kiểm tra trong phần cài đặt lịch của giao diện người dùng web Lịch Google (trong phần "Địa chỉ lịch") hoặc bạn có thể tìm địa chỉ đó trong kết quả của lệnh gọicalendarList.list()
.event
là sự kiện cần tạo với tất cả thông tin chi tiết cần thiết, chẳng hạn như thời gian bắt đầu và thời gian kết thúc. Hai trường bắt buộc duy nhất là thời gianstart
vàend
. Hãy xemevent
tham chiếu để biết toàn bộ các trường sự kiện.
Để tạo sự kiện thành công, bạn cần:
- Đặt phạm vi OAuth thành
https://www.googleapis.com/auth/calendar
để bạn có quyền chỉnh sửa lịch của người dùng. - Đảm bảo người dùng đã xác thực có quyền ghi vào lịch bằng
calendarId
mà bạn cung cấp (ví dụ: bằng cách gọicalendarList.get()
chocalendarId
và kiểm traaccessRole
).
Thêm siêu dữ liệu sự kiện
Bạn có thể tuỳ ý thêm siêu dữ liệu sự kiện khi tạo một sự kiện trên lịch. Nếu chọn không thêm siêu dữ liệu trong quá trình tạo, bạn có thể cập nhật nhiều trường bằng cách sử dụng events.update()
; tuy nhiên, một số trường (chẳng hạn như mã sự kiện) chỉ có thể được đặt trong thao tác events.insert()
.
- Thông tin vị trí
- Việc thêm địa chỉ vào trường vị trí sẽ cho phép các tính năng như "thời gian cần rời đi" hoặc hiển thị bản đồ có chỉ đường.
- Mã sự kiện
- Khi tạo sự kiện, bạn có thể chọn tạo mã sự kiện của riêng mình theo yêu cầu về định dạng của chúng tôi. Nhờ đó, bạn có thể đồng bộ hoá các thực thể trong cơ sở dữ liệu cục bộ với các sự kiện trong Lịch Google. Thao tác này cũng ngăn việc tạo sự kiện trùng lặp nếu thao tác không thành công tại một thời điểm nào đó sau khi được thực thi thành công trong phần phụ trợ Lịch. Nếu bạn không cung cấp mã sự kiện, thì máy chủ sẽ tạo mã sự kiện cho bạn. Hãy xem tài liệu tham khảo về mã sự kiện để biết thêm thông tin.
- Người tham dự
- Sự kiện bạn tạo sẽ xuất hiện trên tất cả Lịch Google chính của những người tham dự mà bạn đã thêm cùng với mã sự kiện. Nếu bạn đặt
sendUpdates
thành"all"
hoặc"externalOnly"
trong yêu cầu chèn, thì những người tham dự tương ứng sẽ nhận được thông báo qua email về sự kiện của bạn. Để tìm hiểu thêm, hãy xem bài viết sự kiện có nhiều người tham dự.
Các ví dụ sau đây minh hoạ cách tạo một sự kiện và thiết lập siêu dữ liệu của sự kiện đó:
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}"
Thêm tệp đính kèm trên Drive vào sự kiện
Bạn có thể đính kèm các tệp Google Drive, chẳng hạn như ghi chú cuộc họp trong Tài liệu, ngân sách trong Trang tính, bản trình bày trong Trang trình bày hoặc bất kỳ tệp Google Drive nào khác có liên quan vào các sự kiện trên lịch. Bạn có thể thêm tệp đính kèm khi tạo sự kiện bằng events.insert()
hoặc sau đó trong quá trình cập nhật, chẳng hạn như bằng events.patch()
Hai bước để đính kèm tệp trên Google Drive vào một sự kiện là:
- Lấy URL
alternateLink
,title
vàmimeType
của tệp từ tài nguyên Files của API Drive, thường là bằng phương thứcfiles.get()
. - Tạo hoặc cập nhật một sự kiện với các trường
attachments
được đặt trong nội dung yêu cầu và tham sốsupportsAttachments
được đặt thànhtrue
.
Ví dụ về mã sau đây minh hoạ cách cập nhật một sự kiện hiện có để thêm tệp đính kèm:
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()
Thêm hội nghị truyền hình và hội nghị qua điện thoại vào sự kiện
Bạn có thể liên kết các sự kiện với hội nghị trên Hangouts và Google Meet để cho phép người dùng họp từ xa qua cuộc gọi điện thoại hoặc cuộc gọi video.
Bạn có thể dùng trường conferenceData
để đọc, sao chép và xoá thông tin chi tiết về hội nghị hiện có; bạn cũng có thể dùng trường này để yêu cầu tạo hội nghị mới. Để cho phép tạo và sửa đổi thông tin chi tiết về hội nghị, hãy đặt tham số yêu cầu conferenceDataVersion
thành 1
.
Hiện tại, có 3 loại conferenceData
được hỗ trợ, như được biểu thị bằng conferenceData.conferenceSolution.key.type
:
- Hangouts cho người tiêu dùng (
eventHangout
) - Hangouts phiên bản cũ dành cho người dùng Google Workspace (không dùng nữa;
eventNamedHangout
) - Google Meet (
hangoutsMeet
)
Bạn có thể tìm hiểu loại hội nghị được hỗ trợ cho một lịch bất kỳ của người dùng bằng cách xem conferenceProperties.allowedConferenceSolutionTypes
trong các bộ sưu tập calendars
và calendarList
. Bạn cũng có thể tìm hiểu xem người dùng có muốn tạo Hangouts cho tất cả các sự kiện mới tạo hay không bằng cách kiểm tra chế độ cài đặt autoAddHangouts
trong bộ sưu tập settings
.
Ngoài type
, conferenceSolution
cũng cung cấp các trường name
và iconUri
mà bạn có thể dùng để biểu thị giải pháp hội nghị như minh hoạ dưới đây:
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);
Bạn có thể tạo một hội nghị mới cho một sự kiện bằng cách cung cấp createRequest
cùng với requestId
mới được tạo. requestId
này có thể là string
ngẫu nhiên. Hội nghị được tạo không đồng bộ, nhưng bạn luôn có thể kiểm tra trạng thái của yêu cầu để cho người dùng biết điều gì đang xảy ra.
Ví dụ: cách yêu cầu tạo hội nghị cho một sự kiện hiện có:
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);
});
Phản hồi ngay lập tức cho lệnh gọi này có thể chưa chứa conferenceData
được điền đầy đủ; điều này được biểu thị bằng mã trạng thái pending
trong trường status. Mã trạng thái sẽ thay đổi thành success
sau khi thông tin hội nghị được điền sẵn. Trường entryPoints
chứa thông tin về những URI video và điện thoại mà người dùng có thể gọi đến.
Nếu muốn lên lịch nhiều sự kiện trên Lịch bằng cùng một thông tin chi tiết về hội nghị, bạn có thể sao chép toàn bộ conferenceData
từ một sự kiện sang một sự kiện khác.
Việc sao chép hữu ích trong một số trường hợp. Ví dụ: giả sử bạn đang phát triển một ứng dụng tuyển dụng thiết lập các sự kiện riêng biệt cho ứng viên và người phỏng vấn. Bạn muốn bảo vệ danh tính của người phỏng vấn, nhưng bạn cũng muốn đảm bảo tất cả người tham gia đều tham gia cùng một cuộc gọi hội nghị.