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 tham số 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 trong việc được sắp xếp tự động. Lịch Google giúp họ chia sẻ kế hoạch và nhắc các em về các chủ đề đó để các em có thể chuẩn bị sẵn sàng mà không bị căng thẳng. Ngoài ra, nhờ vào tích hợp liền mạch các sản phẩm của Google, Google Hiện hành sẽ thông báo cho họ thời gian cần rời đi và Google Maps sẽ hướng dẫn họ tới đ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 danh sách thiết bị của người dùng lịch.

Thêm sự kiện

Để tạo một sự kiện, hãy gọi phương thức Phương thức events.insert() cung cấp tại tối thiểu 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 dùng để 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 bạn không biết địa chỉ email của lịch mà bạn muốn sử dụng, bạn có thể xem lịch này trong phần cài đặt của lịch trên web của Lịch Google Giao diện người dùng (trong phần "Địa chỉ lịch") hoặc bạn có thể tìm kiếm giao diện người dùng trong kết quả của Cuộc 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. Xem Tài liệu tham khảo event cho toàn bộ sự kiện mới.

Để tạo sự kiện thành công, bạn cần phải:

  • Đặt phạm vi của OAuth thành https://www.googleapis.com/auth/calendar để bạn có quyền truy cập 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 bạn 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 một 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 cần khởi hành" hoặc hiển thị bản đồ kèm thông tin 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. Thao tác này cho phép bạn lưu giữ các thực thể trong cơ sở dữ liệu cục bộ của bạn để đồng bộ hoá với các sự kiện trong Lịch Google. Điều này cũng ngăn chặ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 thực thi thành công trong phần phụ trợ của Lịch. Nếu không mã sự kiện được cung cấp, máy chủ sẽ tạo một mã cho bạn. Xem mã sự kiện tham khảo để 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 Từ sendNotifications đến true theo yêu cầu chèn của bạn, người tham dự sẽ cũng sẽ nhận được thông báo qua email về sự kiện. Xem sự kiện với hướng dẫn cho nhiều người tham dự cho 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);
});

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/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 Google Drive các tệp 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ỳ công cụ nào khác các tệp liên quan trên Google Drive với sự kiện trên lịch của bạn. Bạn có thể thêm tệp đính kèm khi bạn 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ư với 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 tệp alternateLink URL, titlemimeType từ Tài nguyên Files API Drive, thường là 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 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();
}

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 sự kiện với Hangouts và Hội nghị truyền hình trên Google Meet tới 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.

Trường conferenceData có thể được dùng để đọc, sao chép và xoá thông tin chi tiết hiện có về hội nghị; nó 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ị, đặt 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 bất kỳ lịch cụ thể nào của một bằng cách xem conferenceProperties.allowedConferenceSolutionTypes trong calendars và Bộ sưu tập 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ả bằng cách kiểm tra chế độ cài đặt autoAddHangouts trong Bộ sưu tập settings.

Ngoài type, conferenceSolution còn cung cấp name và Các trường iconUri mà bạn có thể dùng để trình bày giải pháp hội nghị truyền hình như dưới đây bên dưới:

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ó một requestId mới được tạo có thể là string ngẫu nhiên. Các hội nghị là đượ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 hãy 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);
});

Câu trả lời ngay lập tức cho cuộc gọi này có thể chưa chứa thông tin được điền đầy đủ conferenceData; điều này được biểu thị bằng mã trạng thái pending trong trạng thái . Mã trạng thái chuyển thành success sau khi thông tin hội nghị được cập nhật được điền sẵn. Trường entryPoints chứa thông tin về video và URI điện thoại có sẵn để người dùng của bạn gọi điện.

Nếu bạn muốn lên lịch nhiều sự kiện trên Lịch Google 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 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 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 muốn đảm bảo tất cả những người tham gia đều tham gia cùng một cuộc gọi hội nghị.