고급 캘린더 서비스를 사용하면 Apps Script에서 공개 Google Calendar API를 사용할 수 있습니다. Apps Script의 기본 제공 Calendar 서비스와 마찬가지로 이 API를 사용하면 스크립트가 사용자가 구독하는 추가 캘린더를 비롯하여 사용자의 Google Calendar에 액세스하고 이를 수정할 수 있습니다. 대부분의 경우 내장 서비스가 더 사용하기 쉽지만 이 고급 서비스는 개별 이벤트의 배경 색상 설정을 비롯한 몇 가지 추가 기능을 제공합니다.
참조
이 서비스에 관한 자세한 내용은 공개 Google Calendar API의 참조 문서를 참고하세요. Apps Script의 모든 고급 서비스와 마찬가지로 고급 Calendar 서비스는 공개 API와 동일한 객체, 메서드, 매개변수를 사용합니다. 자세한 내용은 메서드 서명 결정 방법을 참고하세요.
/** * Creates an event in the user's default calendar. * @see https://developers.google.com/calendar/api/v3/reference/events/insert */functioncreateEvent(){constcalendarId='primary';conststart=getRelativeDate(1,12);constend=getRelativeDate(1,13);// event details for creating event.letevent={summary:'LunchMeeting',location:'TheDeli',description:'Todiscussourplansforthepresentationnextweek.',start:{dateTime:start.toISOString()},end:{dateTime:end.toISOString()},attendees:[{email:'gduser1@workspacesample.dev'},{email:'gduser2@workspacesample.dev'}],// Red background. Use Calendar.Colors.get() for the full list.colorId:11};try{// call method to insert/create new event in provided calandarevent=Calendar.Events.insert(event,calendarId);console.log('EventID:'+event.id);}catch(err){console.log('Failedwitherror%s',err.message);}}/** * Helper function to get a new Date object relative to the current date. * @param {number} daysOffset The number of days in the future for the new date. * @param {number} hour The hour of the day for the new date, in the time zone * of the script. * @return {Date} The new date. */functiongetRelativeDate(daysOffset,hour){constdate=newDate();date.setDate(date.getDate()+daysOffset);date.setHours(hour);date.setMinutes(0);date.setSeconds(0);date.setMilliseconds(0);returndate;}
캘린더 나열
다음 예는 사용자의 캘린더 목록에 표시된 캘린더에 관한 세부정보를 검색하는 방법을 보여줍니다.
/** * Lists the calendars shown in the user's calendar list. * @see https://developers.google.com/calendar/api/v3/reference/calendarList/list */functionlistCalendars(){letcalendars;letpageToken;do{calendars=Calendar.CalendarList.list({maxResults:100,pageToken:pageToken});if(!calendars.items||calendars.items.length===0){console.log('Nocalendarsfound.');return;}// Print the calendar id and calendar summaryfor(constcalendarofcalendars.items){console.log('%s(ID:%s)',calendar.summary,calendar.id);}pageToken=calendars.nextPageToken;}while(pageToken);}
/** * Lists the next 10 upcoming events in the user's default calendar. * @see https://developers.google.com/calendar/api/v3/reference/events/list */functionlistNext10Events(){constcalendarId='primary';constnow=newDate();constevents=Calendar.Events.list(calendarId,{timeMin:now.toISOString(),singleEvents:true,orderBy:'startTime',maxResults:10});if(!events.items||events.items.length===0){console.log('Noeventsfound.');return;}for(consteventofevents.items){if(event.start.date){// All-day event.conststart=newDate(event.start.date);console.log('%s(%s)',event.summary,start.toLocaleDateString());continue;}conststart=newDate(event.start.dateTime);console.log('%s(%s)',event.summary,start.toLocaleString());}}
조건부로 이벤트 수정
다음 예는 If-Match 헤더를 사용하여 Calendar 일정을 조건부로 업데이트하는 방법을 보여줍니다. 이 스크립트는 새 이벤트를 만들고 30초 동안 기다린 후 이벤트가 생성된 이후 이벤트 세부정보가 변경되지 않은 경우에만 이벤트를 업데이트합니다.
/** * Creates an event in the user's default calendar, waits 30 seconds, then * attempts to update the event's location, on the condition that the event * has not been changed since it was created. If the event is changed during * the 30-second wait, then the subsequent update will throw a 'Precondition * Failed' error. * * The conditional update is accomplished by setting the 'If-Match' header * to the etag of the new event when it was created. */functionconditionalUpdate(){constcalendarId='primary';conststart=getRelativeDate(1,12);constend=getRelativeDate(1,13);letevent={summary:'LunchMeeting',location:'TheDeli',description:'Todiscussourplansforthepresentationnextweek.',start:{dateTime:start.toISOString()},end:{dateTime:end.toISOString()},attendees:[{email:'gduser1@workspacesample.dev'},{email:'gduser2@workspacesample.dev'}],// Red background. Use Calendar.Colors.get() for the full list.colorId:11};event=Calendar.Events.insert(event,calendarId);console.log('EventID:'+event.getId());// Wait 30 seconds to see if the event has been updated outside this script.Utilities.sleep(30*1000);// Try to update the event, on the condition that the event state has not// changed since the event was created.event.location='TheCoffeeShop';try{event=Calendar.Events.update(event,calendarId,event.id,{},{'If-Match':event.etag});console.log('Successfullyupdatedevent:'+event.id);}catch(e){console.log('Fetchthrewanexception:'+e);}}
조건부로 이벤트 검색
다음 예는 If-None-Match 헤더를 사용하여 캘린더 이벤트를 조건부로 가져오는 방법을 보여줍니다. 스크립트는 새 이벤트를 만든 다음 30초 동안 이벤트의 변경사항을 폴링합니다. 이벤트가 변경될 때마다 새 버전이 가져옵니다.
/** * Creates an event in the user's default calendar, then re-fetches the event * every second, on the condition that the event has changed since the last * fetch. * * The conditional fetch is accomplished by setting the 'If-None-Match' header * to the etag of the last known state of the event. */functionconditionalFetch(){constcalendarId='primary';conststart=getRelativeDate(1,12);constend=getRelativeDate(1,13);letevent={summary:'LunchMeeting',location:'TheDeli',description:'Todiscussourplansforthepresentationnextweek.',start:{dateTime:start.toISOString()},end:{dateTime:end.toISOString()},attendees:[{email:'gduser1@workspacesample.dev'},{email:'gduser2@workspacesample.dev'}],// Red background. Use Calendar.Colors.get() for the full list.colorId:11};try{// insert eventevent=Calendar.Events.insert(event,calendarId);console.log('EventID:'+event.getId());// Re-fetch the event each second, but only get a result if it has changed.for(leti=0;i < 30;i++){Utilities.sleep(1000);event=Calendar.Events.get(calendarId,event.id,{},{'If-None-Match':event.etag});console.log('Neweventdescription:'+event.start.dateTime);}}catch(e){console.log('Fetchthrewanexception:'+e);}}
이벤트 동기화
다음 예는 동기화 토큰을 사용하여 이벤트를 검색하는 방법을 보여줍니다.
Calendar 고급 서비스 요청에 동기화 토큰을 포함하면 생성된 이후 변경된 항목만 결과 응답에 포함되므로 더 효율적으로 처리할 수 있습니다. 동기화 프로세스에 관한 자세한 내용은 리소스 효율적으로 동기화를 참고하세요.
다음 예에서는 위 예시에서 정의된 것과 동일한 getRelativeDate(daysOffset, hour) 메서드를 사용합니다.
/** * Retrieve and log events from the given calendar that have been modified * since the last sync. If the sync token is missing or invalid, log all * events from up to a month ago (a full sync). * * @param {string} calendarId The ID of the calender to retrieve events from. * @param {boolean} fullSync If true, throw out any existing sync token and * perform a full sync; if false, use the existing sync token if possible. */functionlogSyncedEvents(calendarId,fullSync){constproperties=PropertiesService.getUserProperties();constoptions={maxResults:100};constsyncToken=properties.getProperty('syncToken');if(syncToken && !fullSync){options.syncToken=syncToken;}else{// Sync events up to thirty days in the past.options.timeMin=getRelativeDate(-30,0).toISOString();}// Retrieve events one page at a time.letevents;letpageToken;do{try{options.pageToken=pageToken;events=Calendar.Events.list(calendarId,options);}catch(e){// Check to see if the sync token was invalidated by the server;// if so, perform a full sync instead.if(e.message==='Synctokenisnolongervalid,afullsyncisrequired.'){properties.deleteProperty('syncToken');logSyncedEvents(calendarId,true);return;}thrownewError(e.message);}if(events.items && events.items.length===0){console.log('Noeventsfound.');return;}for(consteventofevents.items){if(event.status==='cancelled'){console.log('Eventid%swascancelled.',event.id);return;}if(event.start.date){conststart=newDate(event.start.date);console.log('%s(%s)',event.summary,start.toLocaleDateString());return;}// Events that don't last all day; they have defined start times.conststart=newDate(event.start.dateTime);console.log('%s(%s)',event.summary,start.toLocaleString());}pageToken=events.nextPageToken;}while(pageToken);properties.setProperty('syncToken',events.nextSyncToken);}
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2024-12-21(UTC)"],[[["The Advanced Calendar service in Apps Script allows you to access and modify Google Calendar data using the public Google Calendar API."],["It offers features beyond the built-in Calendar service, such as setting event background colors and using HTTP request headers for conditional updates and retrievals."],["Sample code snippets demonstrate various functionalities like creating, listing, and syncing calendar events, and conditionally modifying or retrieving specific events."],["Before using this advanced service, ensure it's enabled in your Apps Script project settings."],["Refer to the Google Calendar API reference documentation and support guide for detailed information and troubleshooting."]]],[]]