Google Calendar の予定を API で取得 (Python)¶
準備¶
参考) Python クイックスタート - Google Docs
Python 用 Google クライアントライブラリをインストールします。
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
認証情報を生成します。
- Google Cloud の APIs Services にアクセス
- Library から、Google Calendar API を有効化する
- Credentials から、CREATE CREDENTIALS > OAuth client ID
- Application type に Desktop app を選択
- 作成した Credentials の JSON をダウンロードする
認証¶
ダウンロードした Credentials を client_secret.json として保存し、以下のコードを実行することで、API を呼ぶための一時的なアクセストークンを取得します。
from google_auth_oauthlib.flow import InstalledAppFlow
flow = InstalledAppFlow.from_client_secrets_file("client_secret.json", [
"https://www.googleapis.com/auth/calendar.readonly",
])
credentials = flow.run_local_server()
https://www.googleapis.com/auth/calendar.readonly
はこのアクセストークンでアクセスできる権限(スコープ)になります。これ以外にアクセスしたい場合は Google API の OAuth 2.0 スコープ から選択します。
予定の取得¶
from datetime import datetime, timedelta, timezone
from googleapiclient.discovery import build
def list_events(calendar_id: str, start: datetime, end: datetime):
service = build("calendar", "v3", credentials=get_credentials())
res = service.events() \
.list(calendarId=calendar_id, timeMin=start.isoformat(), timeMax=end.isoformat(),
singleEvents=True, orderBy="startTime") \
.execute()
return res["items"]
スタックチャン に読み上げてもらう¶
@robot8080 さんの ChatGPT API搭載AIスタックチャン をインストールした M5Stack に通知してしゃべってもらいました。
now = datetime.now().astimezone(timezone.utc)
items = list_events("primary", now, now + timedelta(minutes=15))
for item in items:
if "dateTime" in item["start"]:
dt = datetime.fromisoformat(item["start"]["dateTime"])
message = dt.strftime("%H時%M分") + " " + item["summary"] + " 予定の時間です"
requests.post("http://192.168.13.56/speech", data={"say": message})