0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cloud Run Functions から Google Calendar に予定を入れてみる

0
Posted at

はじめに

Cloud Run Functions を使って、Google Calendar API 経由で自動的に予定を作成する仕組みを実装しました。

今回は HTTP リクエストをトリガーにして、Google カレンダーに指定のイベントを登録する手順を解説します。

仕組み

  • 予定を入れたい Google Calendar に対して Cloud Run Functions にアタッチしたサービスアカウントのメールアドレスへの共有を許可
  • Cloud Run Functions 内で自身のサービスアカウント認証情報を使って Google Calendar に予定を追加

実際のアーキテクチャ

システム構成は非常にシンプルです。

Architecture.png

  1. Cloud Run Functions:サービスアカウントの認証情報を用いて Authorization トークンを自動取得・付与します。
  2. Google Calendar API:API 経由で設定済みのカレンダー(calendarId)に対して Event insert リクエストを発行します。

実装手順

今回は Python 3.14 を利用した実装手順を解説します。

1. Google Cloud コンソールでの事前設定

  1. Google Calendar API の有効化
    • GCP コンソールの「API とサービス」>「ライブラリ」から Google Calendar API を検索し、有効化します。

enableGoogleCalendarAPI.png

  1. サービスアカウントの作成
    • 「IAM と管理」>「サービスアカウント」から新しいサービスアカウントを作成します

createServcie Account.png

  1. Google カレンダー側の共有設定
    • 予定を追加したい Google カレンダーを開きます。
    • 「設定と共有」>「特定のユーザーまたはグループとの共有」にて、上で作成したサービスアカウントのメールアドレスを追加します。
    • 権限は 「すべての予定の詳細の変更や表示ができます」 を選択します。

ConfigurationOfGoogleCalnedar.png

2. Cloud Run Functions のコード作成

requirements.txt

必要なライブラリとして google-api-python-client と google-auth を指定します。

functions-framework==3.*
google-api-python-client==2.*
google-auth==2.*

main.py

関数のコードを実装します。実行環境である GCP 上では Application Default Credentials (ADC) が働くため、サービスアカウントのキーファイルをコード内に持たせる必要はありません。

import os
import datetime
import functions_framework
from googleapiclient.discovery import build
import google.auth

# 対象のカレンダーID (環境変数または直接指定)
CALENDAR_ID = os.environ.get('CALENDAR_ID')

@functions_framework.http
def add_calendar_event(request):
    request_json = request.get_json(silent=True)
    
    # パラメータ取得
    summary = request_json.get('summary', '無題の予定') if request_json else '無題の予定'
    start_time = request_json.get('start_time') if request_json else None
    end_time = request_json.get('end_time') if request_json else None

    if not start_time or not end_time:
        # デフォルトで「1時間後」の予定を作成
        now = datetime.datetime.now(datetime.timezone.utc)
        start_iso = (now + datetime.timedelta(hours=1)).isoformat()
        end_iso = (now + datetime.timedelta(hours=2)).isoformat()
    else:
        start_iso = start_time
        end_iso = end_time

    try:
        # デフォルトの認証情報を取得 (Cloud Run Functionsに紐づくSAを利用)
        credentials, project = google.auth.default(
            scopes=['https://www.googleapis.com/auth/calendar']
        )
        service = build('calendar', 'v3', credentials=credentials)

        event = {
            'summary': summary,
            'description': 'Cloud Run Functions から自動追加された予定です。',
            'start': {
                'dateTime': start_iso,
                'timeZone': 'Asia/Tokyo',
            },
            'end': {
                'dateTime': end_iso,
                'timeZone': 'Asia/Tokyo',
            },
        }

        # 予定作成 API呼び出し
        created_event = service.events().insert(calendarId=CALENDAR_ID, body=event).execute()
        
        return {
            "status": "success",
            "eventLink": created_event.get('htmlLink'),
            "eventId": created_event.get('id')
        }, 200

    except Exception as e:
        return {"status": "error", "message": str(e)}, 500

3. デプロイ

今回の検証では下記の設定で実施しています。

パラメータ 値
サービスの名前 calendar-test-function
リージョン asia-northeast1
認証 IAM 認証
Ingress 全て
環境変数 変数名: CALENDAR_ID
値: <登録したい Google Calendar の Calendar ID>
サービスアカウント <作成したサービスアカウントのメールアドレス>

作成すると Yaml は下図のように表示されているはずです。
ConfigurationOfCloudRunFunctions.png

検証結果

デプロイ完了後に発行された HTTP URL に対して、Cloud Shell から curl コマンドでテストリクエストを送信しました。

リクエスト

curl -X POST https://add-calendar-event-xxxxx-an.a.run.app \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{
    "summary": "[Test]カレンダー登録",
    "start_time": "2026-09-20T10:00:00+09:00",
    "end_time": "2026-09-20T18:00:00+09:00"
  }'

レスポンス

{
  "status": "success",
  "eventId": "abcdefg1234567890",
  "eventLink": "https://www.google.com/calendar/event?eid=..."
}

CloudShell.png

Google カレンダーを確認したところ、指定した日時(2026年9月20日 10:00〜18:00)に 「[Test]カレンダー登録」 という予定が正常に挿入されていることが確認できました。

ResultOfInsertingGoogleCalendarEvent.png

まとめ

今回は Cloud Run Functions から Google Calendar に予定を入れるというユースケースを想定して検証してみました。実務では、「何らかの作業前に自動で共有カレンダーへ作業予定を入れたい」といった際に活用できるのではないでしょうか。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?