Tạo sự kiện

Hãy tưởng tượng một ứng dụng giúp người dùng tìm 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 sự kiện trên lịch, người dùng sẽ nhận được nhiều trợ giúp trong việc 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 căng thẳng. Ngoài ra, nhờ tích hợp liền mạch các sản phẩm của Google, Google Hiện hành sẽ ping họ về thời gian rời đi và Google Maps sẽ hướng họ tới đị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 các 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() cung cấp ít nhất các thông số sau:

  • calendarId là giá trị nhận dạng lịch và có thể là địa chỉ email của lịch tạo sự kiện, hoặc từ khoá đặc biệt 'primary' 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ình muốn sử dụng, bạn có thể kiểm tra địa chỉ email trong phần cài đặt của lịch trên giao diện người dùng web của Lịch Google (trong phần "Địa chỉ lịch") hoặc tìm trong kết quả của lệnh gọi calendarList.list().
  • event là sự kiện cần tạo có tất cả thông tin chi tiết cần thiết, chẳng hạn như thời điểm bắt đầu và kết thúc. Hai trường bắt buộc duy nhất là startend lần. Hãy xem tài liệu tham khảo về event để 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 phải:

  • Đặ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ọi calendarList.get() cho calendarId và kiểm tra accessRole).

Thêm siêu dữ liệu sự kiện

Bạn có thể thêm siêu dữ liệu sự kiện khi tạo sự kiện trên lịch (không bắt buộc). 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 thiết lập trong thao tác events.insert().

Vị trí

Việc thêm địa chỉ vào trường vị trí sẽ bật các tính năng như

"thời điểm khởi hành" hoặc hiển thị bản đồ cùng với 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

tuân thủ các yêu cầu về định dạng của chúng tôi. Việc này cho phép bạn luôn đồ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 thực thi thành công trong phần phụ trợ của Lịch. Nếu không có mã sự kiện nào được cung cấp, máy chủ sẽ tạo một mã 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 đã đưa vào cùng một mã sự kiện. Nếu bạn đặt sendNotifications thành true trong yêu cầu chèn, thì người tham dự cũng sẽ nhận được thông báo qua email về sự kiện. Hãy xem hướng dẫn về các sự kiện có nhiều người tham dự để biết thêm thông tin.

Các ví dụ sau đây minh hoạ cách tạo sự kiện và thiết lập siêu dữ liệu cho sự kiện:

Go

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

1.199

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

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 trên Google Drive 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 nào khác có liên quan trên Google Drive vào các sự kiện trên lịch của mình. Bạn có thể thêm tệp đính kèm khi tạo sự kiện bằng events.insert() trở lên trong quá trình cập nhật, chẳng hạn như bằng events.patch()

Quá trình đính kèm tệp trên Google Drive vào một sự kiện gồm hai phần:

  1. Lấy URL alternateLink, titlemimeType của tệp qua tài nguyên tệp API Drive, thường bằng phương thức files.get().
  2. Tạo hoặc cập nhật một sự kiện có các trường attachments được đặt trong nội dung yêu cầu và tham số supportsAttachments được đặt thành true.

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

1.199

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ị truyền hình trên HangoutsGoogle Meet để cho phép người dùng họp từ xa thông 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ó; trường này cũng có thể được dùng để 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.

Có 3 loại conferenceData hiện được hỗ trợ, như được biểu thị bằng conferenceData.conferenceSolution.key.type:

  1. Hangouts dành cho người tiêu dùng (eventHangout)
  2. Hangouts phiên bản cũ cho Google Workspace người dùng (không dùng nữa; eventNamedHangout)
  3. Google Meet (hangoutsMeet)

Bạn có thể tìm hiểu loại hội nghị truyền hình nào được hỗ trợ cho mọi lịch cụ thể của người dùng bằng cách xem conferenceProperties.allowedConferenceSolutionTypes trong bộ sưu tập calendarscalendarList. 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 của họ hay không bằng cách kiểm tra chế độ cài đặt autoAddHangouts trong tập hợp settings.

Ngoài type, conferenceSolution cũng cung cấp các trường nameiconUri mà bạn có thể dùng để biểu thị giải pháp hội nghị truyền hình như sau:

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 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. Đâ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 diễn ra.

Ví dụ: cách yêu cầu tạo hội nghị truyền hình 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,
  sendNotifications: true,
  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 trạng thái. Mã trạng thái sẽ chuyển 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ề các URI video và điện thoại hiện có sẵn để người dùng gọi đ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ị truyền hình, bạn có thể sao chép toàn bộ conferenceData từ một sự kiện sang sự kiện khác.

Tính năng sao chép rất hữu ích trong một số trường hợp nhất định. Ví dụ: giả sử bạn đang phát triển một đơn đăng ký tuyển dụng sẽ 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 cũng muốn đảm bảo rằng tất cả những người tham gia tham gia cùng một cuộc gọi hội nghị.