|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Notion APIからイベント情報を取得し、現在時刻以降のイベントをJSONとして保存するスクリプト |
| 4 | +""" |
| 5 | + |
| 6 | +import json |
| 7 | +import os |
| 8 | +from datetime import datetime, timezone, timedelta |
| 9 | +from notion_client import Client |
| 10 | + |
| 11 | +# 日本時間のタイムゾーン |
| 12 | +JST = timezone(timedelta(hours=9)) |
| 13 | + |
| 14 | + |
| 15 | +def get_notion_client(): |
| 16 | + """Notion APIクライアントを初期化""" |
| 17 | + token = os.environ.get("NOTION_API_TOKEN") |
| 18 | + if not token: |
| 19 | + raise ValueError("NOTION_API_TOKEN environment variable is not set") |
| 20 | + return Client(auth=token) |
| 21 | + |
| 22 | + |
| 23 | +def fetch_events_from_notion(notion: Client, database_id: str) -> list: |
| 24 | + """ |
| 25 | + NotionデータベースからJSTの現在時刻以降のイベントのみ取得 |
| 26 | + """ |
| 27 | + now_jst = datetime.now(JST) |
| 28 | + |
| 29 | + # 今日の日付(YYYY-MM-DD形式)を取得 |
| 30 | + today_date = now_jst.date().isoformat() |
| 31 | + |
| 32 | + # Notion APIでフィルタリング(日付プロパティ名: "日付") |
| 33 | + # 今日以降の日付のイベントを取得 |
| 34 | + response = notion.databases.query( |
| 35 | + database_id=database_id, |
| 36 | + filter={ |
| 37 | + "property": "日付", |
| 38 | + "date": { |
| 39 | + "on_or_after": today_date |
| 40 | + } |
| 41 | + }, |
| 42 | + sorts=[ |
| 43 | + { |
| 44 | + "property": "日付", |
| 45 | + "direction": "ascending" |
| 46 | + } |
| 47 | + ] |
| 48 | + ) |
| 49 | + |
| 50 | + results = response.get("results", []) |
| 51 | + |
| 52 | + # ページネーション対応(100件以上の場合) |
| 53 | + while response.get("has_more"): |
| 54 | + response = notion.databases.query( |
| 55 | + database_id=database_id, |
| 56 | + filter={ |
| 57 | + "property": "日付", |
| 58 | + "date": { |
| 59 | + "on_or_after": today_date |
| 60 | + } |
| 61 | + }, |
| 62 | + sorts=[ |
| 63 | + { |
| 64 | + "property": "日付", |
| 65 | + "direction": "ascending" |
| 66 | + } |
| 67 | + ], |
| 68 | + start_cursor=response.get("next_cursor") |
| 69 | + ) |
| 70 | + results.extend(response.get("results", [])) |
| 71 | + |
| 72 | + return results |
| 73 | + |
| 74 | + |
| 75 | +def parse_event(page: dict) -> dict: |
| 76 | + """ |
| 77 | + Notionページデータをイベントオブジェクトに変換 |
| 78 | + 実際のプロパティ名に基づいて実装 |
| 79 | + """ |
| 80 | + properties = page.get("properties", {}) |
| 81 | + |
| 82 | + # 名前(タイトル)の取得 |
| 83 | + name = "" |
| 84 | + name_prop = properties.get("名前") |
| 85 | + if name_prop and name_prop.get("title"): |
| 86 | + name = "".join([t.get("plain_text", "") for t in name_prop["title"]]) |
| 87 | + |
| 88 | + # 日付の取得 |
| 89 | + date_start = None |
| 90 | + date_end = None |
| 91 | + date_prop = properties.get("日付") |
| 92 | + if date_prop and date_prop.get("date"): |
| 93 | + date_data = date_prop["date"] |
| 94 | + date_start = date_data.get("start") |
| 95 | + date_end = date_data.get("end") |
| 96 | + |
| 97 | + # 場所の取得 |
| 98 | + location = "" |
| 99 | + location_prop = properties.get("場所") |
| 100 | + if location_prop and location_prop.get("rich_text"): |
| 101 | + location = "".join([t.get("plain_text", "") for t in location_prop["rich_text"]]) |
| 102 | + |
| 103 | + # 時間の取得 |
| 104 | + time = "" |
| 105 | + time_prop = properties.get("時間") |
| 106 | + if time_prop and time_prop.get("rich_text"): |
| 107 | + time = "".join([t.get("plain_text", "") for t in time_prop["rich_text"]]) |
| 108 | + |
| 109 | + # Live配信(URL)の取得 |
| 110 | + live_stream_url = "" |
| 111 | + live_prop = properties.get("Live配信") |
| 112 | + if live_prop: |
| 113 | + if live_prop.get("url"): |
| 114 | + live_stream_url = live_prop["url"] |
| 115 | + elif live_prop.get("rich_text"): |
| 116 | + live_stream_url = "".join([t.get("plain_text", "") for t in live_prop["rich_text"]]) |
| 117 | + |
| 118 | + # 詳細の取得 |
| 119 | + description = "" |
| 120 | + detail_prop = properties.get("詳細") |
| 121 | + if detail_prop and detail_prop.get("rich_text"): |
| 122 | + description = "".join([t.get("plain_text", "") for t in detail_prop["rich_text"]]) |
| 123 | + |
| 124 | + return { |
| 125 | + "id": page.get("id", ""), |
| 126 | + "name": name, |
| 127 | + "date": { |
| 128 | + "start": date_start, |
| 129 | + "end": date_end |
| 130 | + }, |
| 131 | + "location": location, |
| 132 | + "time": time, |
| 133 | + "live_stream_url": live_stream_url, |
| 134 | + "description": description, |
| 135 | + "notion_url": page.get("url", ""), |
| 136 | + "created_time": page.get("created_time", ""), |
| 137 | + "last_edited_time": page.get("last_edited_time", "") |
| 138 | + } |
| 139 | + |
| 140 | + |
| 141 | +def filter_future_events(events: list, now_jst: datetime) -> list: |
| 142 | + """ |
| 143 | + 現在時刻以降のイベントのみをフィルタリング |
| 144 | + 日付のみの場合は今日の日付なら全て含める(時刻情報がないため) |
| 145 | + """ |
| 146 | + filtered = [] |
| 147 | + |
| 148 | + for event in events: |
| 149 | + date_start = event.get("date", {}).get("start") |
| 150 | + if not date_start: |
| 151 | + continue |
| 152 | + |
| 153 | + # 日付文字列をパース |
| 154 | + try: |
| 155 | + # ISO形式(時刻含む)の場合 |
| 156 | + if "T" in date_start: |
| 157 | + event_datetime = datetime.fromisoformat(date_start.replace("Z", "+00:00")) |
| 158 | + # JSTに変換(UTCの場合は) |
| 159 | + if event_datetime.tzinfo is None: |
| 160 | + event_datetime = event_datetime.replace(tzinfo=JST) |
| 161 | + elif event_datetime.tzinfo.utcoffset(event_datetime).total_seconds() == 0: |
| 162 | + event_datetime = event_datetime.replace(tzinfo=timezone.utc).astimezone(JST) |
| 163 | + # 現在時刻以降かチェック |
| 164 | + if event_datetime >= now_jst: |
| 165 | + filtered.append(event) |
| 166 | + else: |
| 167 | + # 日付のみ(YYYY-MM-DD)の場合 |
| 168 | + event_date = datetime.strptime(date_start, "%Y-%m-%d").date() |
| 169 | + today_date = now_jst.date() |
| 170 | + # 今日以降の日付なら含める |
| 171 | + if event_date >= today_date: |
| 172 | + filtered.append(event) |
| 173 | + except (ValueError, AttributeError) as e: |
| 174 | + print(f"Warning: Could not parse date '{date_start}': {e}") |
| 175 | + continue |
| 176 | + |
| 177 | + return filtered |
| 178 | + |
| 179 | + |
| 180 | +def main(): |
| 181 | + """メイン処理""" |
| 182 | + # 環境変数からデータベースIDを取得 |
| 183 | + database_id = os.environ.get("NOTION_DATABASE_ID") |
| 184 | + if not database_id: |
| 185 | + raise ValueError("NOTION_DATABASE_ID environment variable is not set") |
| 186 | + |
| 187 | + # Notionクライアントを初期化 |
| 188 | + notion = get_notion_client() |
| 189 | + |
| 190 | + # 現在時刻(JST)を取得 |
| 191 | + now_jst = datetime.now(JST) |
| 192 | + |
| 193 | + # イベントを取得 |
| 194 | + print(f"Fetching events from Notion database: {database_id}") |
| 195 | + print(f"Current time (JST): {now_jst.isoformat()}") |
| 196 | + raw_events = fetch_events_from_notion(notion, database_id) |
| 197 | + print(f"Found {len(raw_events)} events from today onwards") |
| 198 | + |
| 199 | + # イベントをパース |
| 200 | + parsed_events = [parse_event(page) for page in raw_events] |
| 201 | + |
| 202 | + # 現在時刻以降のイベントのみをフィルタリング |
| 203 | + events = filter_future_events(parsed_events, now_jst) |
| 204 | + print(f"Filtered to {len(events)} events after current time") |
| 205 | + |
| 206 | + # 出力データを作成 |
| 207 | + output = { |
| 208 | + "generated_at": now_jst.isoformat(), |
| 209 | + "timezone": "Asia/Tokyo", |
| 210 | + "total_count": len(events), |
| 211 | + "events": events |
| 212 | + } |
| 213 | + |
| 214 | + # JSONファイルに保存 |
| 215 | + output_path = "data/events.json" |
| 216 | + os.makedirs(os.path.dirname(output_path), exist_ok=True) |
| 217 | + |
| 218 | + with open(output_path, "w", encoding="utf-8") as f: |
| 219 | + json.dump(output, f, ensure_ascii=False, indent=2) |
| 220 | + |
| 221 | + print(f"Events saved to {output_path}") |
| 222 | + print(json.dumps(output, ensure_ascii=False, indent=2)) |
| 223 | + |
| 224 | + |
| 225 | +if __name__ == "__main__": |
| 226 | + main() |
0 commit comments