0
0

More than 3 years have passed since last update.

GoogleカレンダーAPIを用いて予定への出欠登録を行う

Posted at

はじめに

明けましておめでとうございます。早いもので令和2年(2020年)になりました。
なかなか投稿できておらず、久々の投稿となってしまいました。
2020年も気軽に投稿していければなと思っています。
今回は、前回の記事「GoogleカレンダーAPIを用いてカレンダー一覧を取得する」に続き、
GoogleカレンダーAPIに関する記事です。

やりたいこと

  • Googleカレンダーに登録されてされている予定に対して出席・欠席の登録をAPI経由で行う

私はこのAPIをAlexaスキルに組み込んで、共有カレンダーに対して音声経由で出欠登録できるようにしてみました。

実装

registEvent.js
'use strict';
const url = require('url');
const https = require('https');

const HTTP_RESPONSE_OK = 200;
const ACCESS_TOKEN = 'API実行に必要なアクセストークン';
let calendarId = '対象となるGoogleカレンダーのID';
let eventId = '出欠登録を行う予定のID';
let apiUrl = `https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events/${eventId}`;

// PATCH用オブジェクト
let requestBody = new Object();

requestBody.attendees = [{
    'displayName': '表示名を設定',
    'email': 'メールアドレスを設定',
    'responseStatus': 'accepted', // 出席の場合(欠席の場合は'declined')
}];

// PATCH用JSONデータ
let patchData = JSON.stringify(requestBody, null, 2);

// 実行URL、メソッドの準備
let options = url.parse(apiUrl);

options.method = "PATCH";
options.headers = {
    "Authorization":"Bearer " + ACCESS_TOKEN,
    "Content-Type":"application/json",
    "Content-Length":Buffer.byteLength(patchData),
};

// カレンダー一覧取得のためのAPI
let options = url.parse("https://www.googleapis.com/calendar/v3/users/me/calendarList");
options.method = "GET";
options.headers = {
    "Authorization":"Bearer " + ACCESS_TOKEN,
};

// API問い合わせ開始と、コールバックの記載
let req = https.request(options, (res) => {
    let result;
    if (res.statusCode === HTTP_RESPONSE_OK) {
        result = true;
    } else {
        result = false;
    }

    // 受信データに対する処理なし(定義が必須)
    res.on("data", (d) => {
        // 処理なし
    });

    // 応答終了イベント処理
    res.on("end", () => {
        if (result === true) {
            console.log('出欠情報の更新に成功');
        } else {
            console.log('出欠情報の更新に失敗');
        }
    }); 
});

req.on("error", (e) => {
    console.log('エラー発生');
});

// PATCH用データの送信
req.write(patchData);

// データ送信終了
req.end();

おわりに

GoogleカレンダーAPIに関してはまた投稿するかもしれません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0