LoginSignup
11
10

More than 5 years have passed since last update.

限定共有のGoogleCalendarをLambda(Python)で操作する【cloudpack大阪】

Last updated at Posted at 2016-02-26

ドハマリしたので備忘録。
限定共有にしているGoogleカレンダーをLambda(Python)で操作します。
仕事でやったんですけど、着手一週間前にGoogleのライブラリ更新された悲劇を日本最速でお届けします。

必要なライブラリ

以下、pipで入れてくだしあ

  • httplib2
  • oauth2client
  • google-api-python-client
  • pyCrypto

サービスアカウントの作成

GoogleCalendarにアクセスするために、サービスアカウントと呼ばれる認証用ユーザーを作成する必要があります。

GoogleDeveloperConsole からAPI Managerにアクセスします。

API_ライブラリ_-_msp-calendar.png

CalendarAPIをEnableに。
Calendar_API_-_msp-calendar.png

「API Manager」から「認証情報」へ移動し、サービスアカウントキーを作成。
認証情報_-_msp-calendar.png

名前とサービスアカウントIDを入力してください。
サービスアカウントIDをは後ほど利用します。
また、今回はキータイプp12を指定します。
サービス_アカウントキーの作成_-_msp-calendar 2.png

p12ファイルがDLされるので、pemに変換
openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem

カレンダーの共有設定

作成したサービスアカウントをGoogleカレンダーの共有ユーザーに追加してください。
公式ドキュメントには、ここの記述を見つけられずハマってました。
なりすましユーザーどうこうみたいな記述はあったんですが、追加しないと操作できないっぽいです。

  1. Googleカレンダー右上の歯車から「設定」
  2. 「カレンダー」タブを選択し、「共有:設定を編集」へ アイレット株式会社_-_カレンダー_-_設定.png
  3. 先ほど作成したサービスアカウントを追加 アイレット株式会社_-_カレンダー_-_共有.png

ソースコード

import httplib2
from apiclient import discovery
import oauth2client
from oauth2client.service_account import ServiceAccountCredentials
from datetime import datetime as dt

SERVICE_ACCOUNT_ID = "xxx@xxx.xxx" # 取得したサービスアカウント

def lambda_handler(event, context):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build(
        'calendar',
        'v3',
        http=http
    )

    events = service.events().list(calendarId=CALENDAR_ID).execute()

    return events.get('items', [])


def get_credentials():
    scopes = 'https://www.googleapis.com/auth/calendar'
    credentials = ServiceAccountCredentials.from_p12_keyfile(
        SERVICE_ACCOUNT_ID,
        'key.pem',
        scopes=scopes
    )

    return credentials

あとは lambda-uploader なり自分で圧縮するなりでLambdaにアップすればオッケーです!

11
10
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
11
10