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 làm sự kiện trên lịch, người dùng sẽ được trợ giúp rất nhiều trong việc tự động sắp xếp. Lịch Google giúp họ chia sẻ kế hoạch và nhắc về kế hoạch để họ có thể chuẩn bị sẵn sàng mà không bị 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ẽ hiển thị thông báo về thời điểm rời đi và Google Maps sẽ hướng dẫn người dùng đến địa điểm gặp gỡ đúng giờ.

Bài viết này giải thích cách tạo các 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 bạn 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 web của Lịch Google (trong mục "Địa chỉ lịch") hoặc bạn có thể tìm lịch trong kết quả của cuộc gọi calendarList.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 như bắt đầu và kết thúc. Hai trường bắt buộc duy nhất là startend. Hãy xem tài liệu tham khảo về event để biết tập hợp đầy đủ 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 của bạn 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 về 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 đặt 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 gian khởi hành" hoặc hiển thị bản đồ cùng với chỉ đường.

ID 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

phù hợp với 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. Điều này cũng giúp ngăn việc tạo sự kiện trùng lặp nếu thao tác bị lỗi 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 bạn không cung cấp mã sự kiện, 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, người tham dự cũng sẽ nhận được thông báo qua email cho sự kiện của bạn. 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 một sự kiện và cài đặt 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/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 sự kiện trên lịch của bạn. 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ư với events.patch()

Hai phần của việc đính kèm tệp trên Google Drive vào sự kiện là:

  1. Lấy URL của tệp alternateLink, titlemimeType trong tài nguyên Tệp 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 nội dung yêu cầu và thông số supportsAttachments được đặt thành true.

Mã ví dụ 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 trong HangoutsGoogle Meet để cho phép người dùng gặp gỡ 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 hiện có về hội nghị truyền hình. 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ị truyền hình, hãy đặt tham số yêu cầu conferenceDataVersion thành 1.

Hiện có ba loại conferenceData được hỗ trợ và đượ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 được hỗ trợ trên lịch nhất định của người dùng bằng cách xem conferenceProperties.allowedConferenceSolutionTypes trong các 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 bộ sưu tậ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 cho createRequest với một requestId mới được tạo (có thể là string ngẫu nhiên). Hội nghị truyền hình được tạo không đồng bộ, nhưng bạn luôn có thể kiểm tra trạng thái yêu cầu để cho người dùng biết điều gì đang xảy ra.

Ví dụ: để yêu cầu tạo hội nghị truyền hình cho một sự kiện hiện có, hãy làm như sau:

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 tức thì 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ẽ thay đổi thành success sau khi thông tin về hội nghị truyền hình được điề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 điện.

Nếu muốn lên lịch nhiều sự kiện trên Lịch có cùng 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ừ sự kiện này 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. 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ị.