터미널에서 구글 캘린더에 일정 추가하기

루이쩐·2022년 2월 10일
0

사용법

  1. 아래에 첨부한 index.js 생성

  2. 구글 캘린더 앱 접근 권한 부여 받기

    1. https://developers.google.com/calendar/quickstart/nodejs 에서 “Enable Google Calendar API” 클릭
    2. 앱 이름 임의로 지정하고 클라이언트 종류는 "데스크톱" 선택
    3. credentials.json 을 index.js와 같은 디렉토리에 다운로드
  3. 구글 API 패키지 받기

    같은 디렉토리에 npm install googleapis@39 --save & npm install moment

  4. 캘린더 ID, 색 설정

    index.js 에 들어가 ID와 색 설정

  5. 끝!

    이제부터 새 스케줄을 CLI로 추가 할 수 있다! 아래 명령어를 입력하여 테스트해보자. 2022년2월22일 한국시간 오전 9시부터 3시간동안 '글쓰기' 이벤트를 추가한다.

    node . 2022-02-22 09:00 3 '글쓰기'

    *처음 구동할때 인증 URL에 들어가서 받은 토큰을 터미널에 복붙하라는 명령이 뜰 것. 하라는대로 하면 됨.

// index.js

const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");
const moment = require("moment");

// 직접 설정할 변수
const MY_CALENDAR =
  "XXXXXXXXX@group.calendar.google.com"; // 캘린더 ID
const COLOR_ID = 2; // 이벤트 색 (1: '#a4bdfc', 2: '#7ae7bf', 3: '#dbadff', 4: '#ff887c', 5: '#fbd75b', 6: '#ffb878', 7: '#46d6db', 8: '#e1e1e1', 9: '#5484ed', 10: '#51b749', 11: '#dc2127')

// If modifying these scopes, delete token.json.
const SCOPES = ["https://www.googleapis.com/auth/calendar"];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = "token.json";

// Load client secrets from a local file.
fs.readFile("credentials.json", (err, content) => {
  if (err) return console.log("Error loading client secret file:", err);
  // Authorize a client with credentials, then call the Google Calendar API.
  authorize(JSON.parse(content), createEvent);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const { client_secret, client_id, redirect_uris } = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
    client_id,
    client_secret,
    redirect_uris[0]
  );

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: "offline",
    scope: SCOPES,
  });
  console.log("Authorize this app by visiting this url:", authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question("Enter the code from that page here: ", (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error("Error retrieving access token", err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log("Token stored to", TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Create an event on Couch Coding calendar.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function createEvent(auth) {
  const startDate = process.argv[2]; // 2022-02-22
  const startTime = process.argv[3]; // 09:00
  const numHour = process.argv[4];
  const name = process.argv[5];

  const startDateTime = `${startDate}T${startTime}:00+09:00`;
  const startTimeUTC = new Date(startDateTime); // 2022-02-22T00:00:00Z
  const endDateTime = moment(startDateTime).add(numHour, "h");
  const endTimeUTC = new Date(endDateTime);

  const event = {
    summary: `${name} (${numHour}h)`,
    start: { dateTime: startTimeUTC, timeZone: "Asia/Seoul" },
    end: { dateTime: endTimeUTC, timeZone: "Asia/Seoul" },
    colorId: COLOR_ID,
  };
  const calendar = google.calendar({ version: "v3", auth });
  calendar.events.insert(
    {
      calendarId: MY_CALENDAR,
      resource: event,
    },
    (err, res) => {
      if (err) return console.log("The API returned an error: " + err);
      console.log("Event created: %s", res.data);
    }
  );
}

0개의 댓글